Browse Source

AES加密 ECB模式 处理完成

main
sunyufeng 1 year ago
parent
commit
453f18c53a

+ 24
- 18
iOSFirst/network/NetworkManager.swift View File

91
 // 插件,实现pluginType可以实现在网络请求前转菊花,请求完成结束转菊花,或者写日志等功能
91
 // 插件,实现pluginType可以实现在网络请求前转菊花,请求完成结束转菊花,或者写日志等功能
92
 struct NetworkPlugin: PluginType {
92
 struct NetworkPlugin: PluginType {
93
     let userDefault=UserDefaults.standard
93
     let userDefault=UserDefaults.standard
94
-
94
+    
95
     /// Called to modify a request before sending.(可进行数据加密等)
95
     /// Called to modify a request before sending.(可进行数据加密等)
96
     func prepare(_ request: URLRequest, target: TargetType) -> URLRequest {
96
     func prepare(_ request: URLRequest, target: TargetType) -> URLRequest {
97
         var mRequest = request
97
         var mRequest = request
98
         let key = "XINGHUOLIAOYUAN7"
98
         let key = "XINGHUOLIAOYUAN7"
99
-        let jsonString = AESEncryptor.aes_encrypt(request.httpBody!.toHexString(),aes_key: key)
100
-//        mRequest.httpBody = jsonString.data(using: String.Encoding.utf8)
99
+//        let jsonString = AESEncryptor.aes_encrypt(request.httpBody!.toHexString(),aes_key: key)
100
+        //TODO AES加密相关
101
+        let jsonString =  aesEncryptData(request.httpBody,key.data(using: .utf8))
102
+     
103
+//        let jsonString = AESEncryptor.aes_encrypt(request.httpBody!.toHexString(),aes_key: key)
104
+        //TODO AES加密相关
105
+//        let jsonString =  aesEncryptString(String(data: request.httpBody!, encoding: String.Encoding.utf8) ?? "",key)
106
+        mRequest.httpBody = jsonString?.toHexString().data(using: .utf8)
101
         print("""
107
         print("""
102
                          #############↓网络请求参数↓#################
108
                          #############↓网络请求参数↓#################
103
                          \(target.baseURL)\(target.path)
109
                          \(target.baseURL)\(target.path)
104
-                         \(jsonString ?? "无参数")
110
+                         \(jsonString?.toHexString() ?? "无参数")
105
                          #############↑网络请求参数↑#################
111
                          #############↑网络请求参数↑#################
106
                          """)
112
                          """)
107
         let userinfo = NSKeyedUnarchiver.unarchiveObject(with: userDefault.object(forKey: "userinfo") as! Data ) as! LoginUserInfo
113
         let userinfo = NSKeyedUnarchiver.unarchiveObject(with: userDefault.object(forKey: "userinfo") as! Data ) as! LoginUserInfo
123
     
129
     
124
     /// Called immediately before a request is sent over the network (or stubbed).(可进行网络等待,loading等)
130
     /// Called immediately before a request is sent over the network (or stubbed).(可进行网络等待,loading等)
125
     func willSend(_ request: RequestType, target: TargetType) {
131
     func willSend(_ request: RequestType, target: TargetType) {
126
-//        guard let target = target as? AccountService else { return }
127
-//        let jsonData = try? JSONSerialization.data(withJSONObject: target.parameters, options: .prettyPrinted)
128
-//                let jsonString = String(data: jsonData ?? Data(), encoding: .utf8)
129
-//                print("""
130
-//                    #############↓网络请求参数↓#################
131
-//                    \(target.baseURL)\(target.path)
132
-//                    \(jsonString ?? "无参数")
133
-//                    #############↑网络请求参数↑#################
134
-//                    """)
132
+        //        guard let target = target as? AccountService else { return }
133
+        //        let jsonData = try? JSONSerialization.data(withJSONObject: target.parameters, options: .prettyPrinted)
134
+        //                let jsonString = String(data: jsonData ?? Data(), encoding: .utf8)
135
+        //                print("""
136
+        //                    #############↓网络请求参数↓#################
137
+        //                    \(target.baseURL)\(target.path)
138
+        //                    \(jsonString ?? "无参数")
139
+        //                    #############↑网络请求参数↑#################
140
+        //                    """)
135
         
141
         
136
     }
142
     }
137
-
143
+    
138
     /// Called after a response has been received, but before the MoyaProvider has invoked its completion handler.(loading结束等)
144
     /// Called after a response has been received, but before the MoyaProvider has invoked its completion handler.(loading结束等)
139
     func didReceive(_ result: Result<Response, MoyaError>, target: TargetType) {
145
     func didReceive(_ result: Result<Response, MoyaError>, target: TargetType) {
140
-    
146
+        
141
     }
147
     }
142
-
148
+    
143
     /// Called to modify a result before completion.(可进行数据解密等)
149
     /// Called to modify a result before completion.(可进行数据解密等)
144
     func process(_ result: Result<Response, MoyaError>, target: TargetType) -> Result<Response, MoyaError> {
150
     func process(_ result: Result<Response, MoyaError>, target: TargetType) -> Result<Response, MoyaError> {
145
         return result
151
         return result
146
     }
152
     }
147
-
153
+    
148
 }
154
 }
149
 
155
 
150
 
156
 
211
         
217
         
212
         // 错误处理 - 弹出错误信息
218
         // 错误处理 - 弹出错误信息
213
         func failureHandle(failure: ((Int?, String) ->Void)? , stateCode: Int?, message: String) {
219
         func failureHandle(failure: ((Int?, String) ->Void)? , stateCode: Int?, message: String) {
214
-//            Alert.show(type: .error, text: message)
220
+            //            Alert.show(type: .error, text: message)
215
             //弹出错误信息
221
             //弹出错误信息
216
             failure?(stateCode ,message)
222
             failure?(stateCode ,message)
217
         }
223
         }

+ 1
- 1
iOSFirst/network/service/AccountService.swift View File

76
         case .login(_, _, let showLoading):
76
         case .login(_, _, let showLoading):
77
 
77
 
78
             return [
78
             return [
79
-                "st":"false",
79
+                "st":"true",
80
                 "Content-type":"application/json"]
80
                 "Content-type":"application/json"]
81
         default:
81
         default:
82
             return nil
82
             return nil

+ 21
- 0
iOSFirst/util/AESCipher.h View File

1
+//
2
+//  AESCipher.h
3
+//  iOSFirst
4
+//
5
+//  Created by 孙宇峰 on 2023/3/2.
6
+//
7
+
8
+#ifndef AESCipher_h
9
+#define AESCipher_h
10
+#import <Foundation/Foundation.h>
11
+
12
+
13
+#endif /* AESCipher_h */
14
+
15
+
16
+NSString * aesEncryptString(NSString *content, NSString *key);
17
+NSString * aesDecryptString(NSString *content, NSString *key);
18
+
19
+NSData * aesEncryptData(NSData *data, NSData *key);
20
+NSData * aesDecryptData(NSData *data, NSData *key);
21
+

+ 85
- 0
iOSFirst/util/AESCipher.m View File

1
+//
2
+//  AESCipher.m
3
+//  iOSFirst
4
+//
5
+//  Created by 孙宇峰 on 2023/3/2.
6
+//
7
+
8
+#import <Foundation/Foundation.h>
9
+#import "AESCipher.h"
10
+#import <CommonCrypto/CommonCryptor.h>
11
+
12
+NSString const *kInitVector = @"x00/x00/x00/x00/x00/x00/x00/x00";
13
+size_t const kKeySize = kCCKeySizeAES128;
14
+
15
+NSData * cipherOperation(NSData *contentData, NSData *keyData, CCOperation operation) {
16
+    NSUInteger dataLength = contentData.length;
17
+    
18
+    void const *initVectorBytes = [kInitVector dataUsingEncoding:NSUTF8StringEncoding].bytes;
19
+    void const *contentBytes = contentData.bytes;
20
+    void const *keyBytes = keyData.bytes;
21
+    
22
+    size_t operationSize = dataLength + kCCBlockSizeAES128;
23
+    void *operationBytes = malloc(operationSize);
24
+    if (operationBytes == NULL) {
25
+        return nil;
26
+    }
27
+    size_t actualOutSize = 0;
28
+    
29
+    CCCryptorStatus cryptStatus = CCCrypt(operation,
30
+                                          kCCAlgorithmAES128,
31
+                                          kCCOptionPKCS7Padding|kCCOptionECBMode,
32
+                                          keyBytes,
33
+                                          kCCKeySizeAES128,
34
+                                          nil,
35
+                                          contentBytes,
36
+                                          dataLength,
37
+                                          operationBytes,
38
+                                          operationSize,
39
+                                          &actualOutSize);
40
+    
41
+    if (cryptStatus == kCCSuccess) {
42
+        return [NSData dataWithBytesNoCopy:operationBytes length:actualOutSize];
43
+    }
44
+    free(operationBytes);
45
+    operationBytes = NULL;
46
+    return nil;
47
+}
48
+
49
+NSString * aesEncryptString(NSString *content, NSString *key) {
50
+    NSCParameterAssert(content);
51
+    NSCParameterAssert(key);
52
+    
53
+    NSData *contentData = [content dataUsingEncoding:NSUTF8StringEncoding];
54
+    NSData *keyData = [key dataUsingEncoding:NSUTF8StringEncoding];
55
+    NSData *encrptedData = aesEncryptData(contentData, keyData);
56
+    return [encrptedData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
57
+}
58
+
59
+NSString * aesDecryptString(NSString *content, NSString *key) {
60
+    NSCParameterAssert(content);
61
+    NSCParameterAssert(key);
62
+    
63
+    NSData *contentData = [[NSData alloc] initWithBase64EncodedString:content options:NSDataBase64DecodingIgnoreUnknownCharacters];
64
+    NSData *keyData = [key dataUsingEncoding:NSUTF8StringEncoding];
65
+    NSData *decryptedData = aesDecryptData(contentData, keyData);
66
+    return [[NSString alloc] initWithData:decryptedData encoding:NSUTF8StringEncoding];
67
+}
68
+
69
+NSData * aesEncryptData(NSData *contentData, NSData *keyData) {
70
+    NSCParameterAssert(contentData);
71
+    NSCParameterAssert(keyData);
72
+    
73
+    NSString *hint = [NSString stringWithFormat:@"The key size of AES-%lu should be %lu bytes!", kKeySize * 8, kKeySize];
74
+    NSCAssert(keyData.length == kKeySize, hint);
75
+    return cipherOperation(contentData, keyData, kCCEncrypt);
76
+}
77
+
78
+NSData * aesDecryptData(NSData *contentData, NSData *keyData) {
79
+    NSCParameterAssert(contentData);
80
+    NSCParameterAssert(keyData);
81
+    
82
+    NSString *hint = [NSString stringWithFormat:@"The key size of AES-%lu should be %lu bytes!", kKeySize * 8, kKeySize];
83
+    NSCAssert(keyData.length == kKeySize, hint);
84
+    return cipherOperation(contentData, keyData, kCCDecrypt);
85
+}

Loading…
Cancel
Save