现在网上大多数的AES加密ECB模式很多,CBC很少,最近公司项目要求加密,并且秘钥和偏移量并不是直接给出的:需要自己处理,取出32位的key和16位iv,废话不说,直接上核心代码:
.m文件:
size_t const kKeySize = kCCKeySizeAES256;
NSData * cipherOperation(NSData *contentData, NSData *keyData, CCOperation operation) {
NSUInteger dataLength = contentData.length;
size_t operationSize = dataLength + kCCBlockSizeAES128;
void *operationBytes = malloc(operationSize);
size_t actualOutSize = 0;
//获取iv偏移量16位
NSRange ivRange={0,16};
Byte *ivByte =(Byte*)[[keyData subdataWithRange:ivRange]bytes];
//获取key32位
NSRange keyRange={0,32};
Byte *keyByte =(Byte*)[[keyData subdataWithRange:keyRange]bytes];
// void const *initVectorBytes =iviv;//偏移量
void const *contentBytes = contentData.bytes;//内容
CCCryptorStatus cryptStatus = CCCrypt(operation,
kCCAlgorithmAES128,
kCCOptionPKCS7Padding,
keyByte,//秘钥
kKeySize,
ivByte,//偏移量
contentBytes,//内容
dataLength,
operationBytes,
operationSize,
&actualOutSize);
if (cryptStatus == kCCSuccess) {
return [NSData dataWithBytesNoCopy:operationBytes length:actualOutSize];
}
free(operationBytes);
return nil;
}
NSString * aesEncryptString(NSString *content, NSString *key) {
NSData *contentData = [content dataUsingEncoding:NSUTF8StringEncoding];
NSData *keyData = [GTMBase64 decodeString:key];
NSData *encrptedData = aesEncryptData(contentData, keyData);
return [encrptedData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
}
NSString * aesDecryptString(NSString *content, NSString *key) {
NSData *contentData = [[NSData alloc] initWithBase64EncodedString:content options:NSDataBase64DecodingIgnoreUnknownCharacters];
NSData *keyData = [GTMBase64 decodeString:key];
NSData *decryptedData = aesDecryptData(contentData, keyData);
return [[NSString alloc] initWithData:decryptedData encoding:NSUTF8StringEncoding];
}
NSData * aesEncryptData(NSData *contentData, NSData *keyData) {
// NSString *hint = [NSString stringWithFormat:@"The key size of AES-%lu should be %lu bytes!", kKeySize * 8, kKeySize];
// NSCAssert(keyData.length == kKeySize, hint);
return cipherOperation(contentData, keyData, kCCEncrypt);
}
NSData * aesDecryptData(NSData *contentData, NSData *keyData) {
// NSString *hint = [NSString stringWithFormat:@"The key size of AES-%lu should be %lu bytes!", kKeySize * 8, kKeySize];
// NSCAssert(keyData.length == kKeySize, hint);
return cipherOperation(contentData, keyData, kCCDecrypt);
}
注:此处的keyData是通过base64解码的。
ios的代码是按照下面安卓的代码写的:(送给那些遇到这些坑的孩子)