项目里有些时候需要用AES来进行接口加密,密钥分为固定密钥和动态密钥,一般固定密钥写死在app内,将登录的信息用固定密钥加密,放在登录的时候进行验证,验证通过后,会返回动态密钥,前端保存下来,调用加密接口时,用动态密钥进行加密。
首先是 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) {
// 对加密后的数据进行 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
接着就是需要加密的接口了,一般写在公共的网络请求类里,顺便说一下,一般加密接口都是 POST 请求,一般还需要带 token 请求头,设备信息等等,涉及到别的类,就不写进来了。
// 创建会话管理者
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
// 设置请求方式为 POST 并填入 url 地址(要对 url 处理,记得写在前面,不然给 url 加后缀没用)
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:url parameters:nil error:nil];
// 判断要请求的接口是不是登录加密接口
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 的动态密钥
keyToken = [UserInfoTool shareInstance].keyToken;
}
// 这句代码是把字典转 JSON 字符串,params 是你要传的参数字典
NSString *str = [Utils convertToJsonData:params];
// 将 JSON 字符串进行 AES 加密
NSString *AesStr = [AES128 AES128Encrypt:str key:keyToken];
// 设置接收格式
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
// 设置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 的方式请求
[[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) {
// 把返回对象转成 JSON,再转成字典
id json = [self decrypeJsonWithData:responseObject];
if ([json isKindOfClass:[NSDictionary class]]) {
NSDictionary *dic = (NSDictionary *)json;
// 把转化成功的字典回调出去
[self successWithData:dic success:success failure:failure];
}
}
}
else {
errors(error);
[self failureWithError:error];
}
}] resume];
- (id)decrypeJsonWithData:(NSData *)data {
// 转成字符串
NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
// 转成json对象
return [NSJSONSerialization JSONObjectWithData:[jsonStr dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
}