公司要求用AES/ECB/PKCS5Paddina加密,之前没有做过,流程是这样的
生成AES密钥key,服务端的要求是128bit = 16byte,其实就是一个16位的随机字符串.
/**
随机生成16位字符串key
*/
+ (NSString *)randomlyGenerated16BitString
{
NSString *string = [[NSString alloc]init];
for(inti =0; i <16; i++) {
intnumber =arc4random() %36;
if(number <10) {
intfigure =arc4random() %10;
NSString*tempString = [NSStringstringWithFormat:@"%d", figure];
string = [stringstringByAppendingString:tempString];
}else{
intfigure = (arc4random() %26) +97;
charcharacter = figure;
NSString*tempString = [NSStringstringWithFormat:@"%c", character];
string = [stringstringByAppendingString:tempString];
}
}
return string;
}
下一步就是进行AES/ECB/PKCS5Paddina加密,网上找了很多,但是服务端都是不通的,找了几个博客,合并了一下,就可以了
/**
AES128/ECB/PKCS5Paddina 加密
*/
+ (NSMutableDictionary *)encryptAES:(NSString *)content key:(NSString *)key{
NSData *contentData = [content dataUsingEncoding:NSUTF8StringEncoding];
NSUIntegerdataLength = contentData.length;
// 为结束符'\0' +1
charkeyPtr[kCCKeySizeAES128+1];
memset(keyPtr,0,sizeof(keyPtr));
[keygetCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
// 密文长度 <= 明文长度 + BlockSize
size_tencryptSize = dataLength +kCCBlockSizeAES128;
void*encryptedBytes =malloc(encryptSize);
size_tactualOutSize =0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
kCCAlgorithmAES128,
kCCOptionPKCS7Padding|kCCOptionECBMode, //CBC -> PKCS7Padding,ECB -> kCCOptionPKCS7Padding|kCCOptionECBMode
keyPtr,
kCCKeySizeAES128,
NULL,
contentData.bytes,
dataLength,
encryptedBytes,
encryptSize,
&actualOutSize);
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
if(cryptStatus ==kCCSuccess) {
NSData*data = [NSData dataWithBytesNoCopy:encryptedByteslength:actualOutSize];
// 如果服务端只是需要一个base64字符串 返回[data base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed]就可以了,但是我们服务端要base64解码后的MD5,然而得到的base64字符串解码后为空,鄙人没找到解决方案,只能给data进行MD5加密,一般的公司是用不到MD5加密的,返回base64字符串就可以了
[dicsetValue:[BDVerificationTool getMD5WithData:data] forKey:@"enc_md5_data"];
[dicsetValue:[data base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed] forKey:@"enc_data"];
returndic;
}
free(encryptedBytes);
return nil;
}
/**
data MD5加密
*/
+ (NSString*)getMD5WithData:(NSData*)data{
//1: 创建一个MD5对象
CC_MD5_CTX md5;
//2: 初始化MD5
CC_MD5_Init(&md5);
//3: 准备MD5加密
CC_MD5_Update(&md5, data.bytes, (uint32_t)data.length);
//4: 准备一个字符串数组, 存储MD5加密之后的数据
unsigned char result[CC_MD5_DIGEST_LENGTH];
//5: 结束MD5加密
CC_MD5_Final(result, &md5);
NSMutableString *resultString = [NSMutableString string];
//6:从result数组中获取最终结果
for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
[resultString appendFormat:@"%02x", result[i]];
}
returnresultString;
}