項(xiàng)目里有些時(shí)候需要用AES來進(jìn)行接口加密,密鑰分為固定密鑰和動(dòng)態(tài)密鑰嚎莉,一般固定密鑰寫死在app內(nèi)腿椎,將登錄的信息用固定密鑰加密桌硫,放在登錄的時(shí)候進(jìn)行驗(yàn)證,驗(yàn)證通過后啃炸,會(huì)返回動(dòng)態(tài)密鑰铆隘,前端保存下來,調(diào)用加密接口時(shí)南用,用動(dòng)態(tài)密鑰進(jìn)行加密膀钠。
首先是 AES 加密類(.h):
#import <Foundation/Foundation.h>
@interface AES128 : NSObject
+(NSString *)AES128Encrypt:(NSString *)plainText key:(NSString *)key;//加密
+(NSString *)AES128Decrypt:(NSString *)encryptText key:(NSString *)key; //解密
@end
接著是 .m 文件
#import "AES128.h"
#import <CommonCrypto/CommonCryptor.h>
@implementation AES128
+( NSString *)AES128Encrypt:(NSString *)plainText key:(NSString *)key
{
char keyPtr[kCCKeySizeAES128+1];
memset(keyPtr, 0, sizeof(keyPtr));
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
NSData* data = [plainText dataUsingEncoding:NSUTF8StringEncoding];
NSUInteger dataLength = [data length];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
kCCAlgorithmAES128,
kCCOptionPKCS7Padding|kCCOptionECBMode,
keyPtr,
kCCBlockSizeAES128,
NULL,
[data bytes],
dataLength,
buffer,
bufferSize,
&numBytesEncrypted);
if (cryptStatus == kCCSuccess) {
// 對(duì)加密后的數(shù)據(jù)進(jìn)行 base64 編碼
return [[NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted] base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
}
free(buffer);
return nil;
}
+ (NSString *)AES128Decrypt:(NSString *)encryptText key:(NSString *)key; //解密
{
char keyPtr[kCCKeySizeAES128 + 1];
memset(keyPtr, 0, sizeof(keyPtr));
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
NSData *data = [[NSData alloc] initWithBase64EncodedString:encryptText options:NSDataBase64DecodingIgnoreUnknownCharacters];
NSUInteger dataLength = [data length];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
size_t numBytesCrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,
kCCAlgorithmAES128,
0x0000|kCCOptionECBMode|kCCOptionPKCS7Padding,
keyPtr,
kCCBlockSizeAES128,
NULL,
[data bytes],
dataLength,
buffer,
bufferSize,
&numBytesCrypted);
if (cryptStatus == kCCSuccess) {
return [[NSString alloc] initWithData:[NSData dataWithBytesNoCopy:buffer length:numBytesCrypted] encoding:NSUTF8StringEncoding];
}
free(buffer);
return nil;
}
@end
接著就是需要加密的接口了,一般寫在公共的網(wǎng)絡(luò)請(qǐng)求類里裹虫,順便說一下肿嘲,一般加密接口都是 POST 請(qǐng)求,一般還需要帶 token 請(qǐng)求頭恒界,設(shè)備信息等等睦刃,涉及到別的類,就不寫進(jìn)來了十酣。
// 創(chuàng)建會(huì)話管理者
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
// 設(shè)置請(qǐng)求方式為 POST 并填入 url 地址(要對(duì) url 處理涩拙,記得寫在前面,不然給 url 加后綴沒用)
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:url parameters:nil error:nil];
// 判斷要請(qǐng)求的接口是不是登錄加密接口
NSString *keyToken = @"";
if ([url containsString:sign_in_phone_pass_URL] || [url containsString:sign_in_mail_pass_URL] || [url containsString:sign_up_phone_pass_URL] || [url containsString:sign_up_mail_pass_URL]) {
// 是登錄加密接口耸采,使用固定密鑰
keyToken = KeyToken;
}
else {
// 不是登錄加密接口兴泥,使用保存在 userDeafult 的動(dòng)態(tài)密鑰
keyToken = [UserInfoTool shareInstance].keyToken;
}
// 這句代碼是把字典轉(zhuǎn) JSON 字符串,params 是你要傳的參數(shù)字典
NSString *str = [Utils convertToJsonData:params];
// 將 JSON 字符串進(jìn)行 AES 加密
NSString *AesStr = [AES128 AES128Encrypt:str key:keyToken];
// 設(shè)置接收格式
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
// 設(shè)置body
[request setHTTPBody:[AesStr dataUsingEncoding:NSUTF8StringEncoding]];
AFHTTPResponseSerializer *responseSerializer = [AFHTTPResponseSerializer serializer];
responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
@"text/html",
@"text/json",
@"text/javascript",
@"text/plain",
nil];
manager.responseSerializer = responseSerializer;
// 需要使用 dataTask 的方式請(qǐng)求
[[manager dataTaskWithRequest:request uploadProgress:^(NSProgress * _Nonnull uploadProgress) {
} downloadProgress:^(NSProgress * _Nonnull downloadProgress) {
} completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (!error) {
if (responseObject) {
// 把返回對(duì)象轉(zhuǎn)成 JSON虾宇,再轉(zhuǎn)成字典
id json = [self decrypeJsonWithData:responseObject];
if ([json isKindOfClass:[NSDictionary class]]) {
NSDictionary *dic = (NSDictionary *)json;
// 把轉(zhuǎn)化成功的字典回調(diào)出去
[self successWithData:dic success:success failure:failure];
}
}
}
else {
errors(error);
[self failureWithError:error];
}
}] resume];
- (id)decrypeJsonWithData:(NSData *)data {
// 轉(zhuǎn)成字符串
NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
// 轉(zhuǎn)成json對(duì)象
return [NSJSONSerialization JSONObjectWithData:[jsonStr dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
}