简单 C语言 AES 加密:
.h
@interface AESTool : NSObject
/**NSData加密*/
NSData * aesCodeEncryptData(NSData *contentData);
/**NSData解密*/
NSData * aesCodeDecryptData(NSData *contentData);
@end
.m
//一定要记得倒入头文件
#import <CommonCrypto/CommonCryptor.h>
size_t const kCodeKeySize = kCCKeySizeAES128;
@implementation AESTool
/*
data加密
*/
NSData * aesCodeEncryptData(NSData *contentData) {
NSCParameterAssert(contentData);
//进行加密操作
return cipherCodeOperation(contentData, kCCEncrypt);
}
/*
data解密
*/
NSData * aesCodeDecryptData(NSData *contentData) {
NSCParameterAssert(contentData);
//进行解密操作
return cipherCodeOperation(contentData, kCCDecrypt);
}
/*
加密解密最根本的方法,分配内存,进行处理,返回结果,清空内存
*/
NSData * cipherCodeOperation(NSData *contentData, CCOperation operation) {
/**{189,183,54,17,106,95,114,246,134,83,157,160,16,172,64,99}*/
/**189 183 54 17 106 95 114 246
134 83 157 160 16 172 64 99
*/
//加密key
Byte SECRET_KEY[16] = {};
SECRET_KEY[0] = 0x16;
SECRET_KEY[1] = 0xB1;
SECRET_KEY[2] = 0x71;
SECRET_KEY[3] = 0x62;
SECRET_KEY[4] = 0x2D;
SECRET_KEY[5] = 0x21;
SECRET_KEY[6] = 0x21;
SECRET_KEY[7] = 0x30;
SECRET_KEY[8] = 0x3C;
SECRET_KEY[9] = 0x22;
SECRET_KEY[10] = 0xA4;
SECRET_KEY[11] = 0x12;
SECRET_KEY[12] = 0xA3;
SECRET_KEY[13] = 0xAE;
SECRET_KEY[14] = 0xCD;
SECRET_KEY[15] = 0xC8;
char *keyPtr = (char*)[NSData dataWithBytes:SECRET_KEY length:sizeof(SECRET_KEY)].bytes;
//加密iv
Byte IVKEY[16] = {};
IVKEY[0] = 0;
IVKEY[1] = 1;
IVKEY[2] = 2;
IVKEY[3] = 3;
IVKEY[4] = 4;
IVKEY[5] = 5;
IVKEY[6] = 6;
IVKEY[7] = 7;
IVKEY[8] = 8;
IVKEY[9] = 9;
IVKEY[10] = 10;
IVKEY[11] = 11;
IVKEY[12] = 12;
IVKEY[13] = 13;
IVKEY[14] = 14;
IVKEY[15] = 15;
char *iv = (char*)[NSData dataWithBytes:IVKEY length:sizeof(IVKEY)].bytes;
//得到内容的byte个数
void const *contentBytes = contentData.bytes;
//得到key的byte个数
//加密内容的长度
NSUInteger dataLength = contentData.length;
//本身长度 +为了防止最后一个明(密)文块不完整,所以加上16bytes
size_t operationSize = dataLength + kCCBlockSizeAES128;
//内存自动分配函数,最后得到的是一个自动分配的存储区,operationBytes是地址,此存储区的初始内容不确定,如果失败返回NULL
void *operationBytes = malloc(operationSize);
if (operationBytes == NULL) {
return nil;
}
//初始化输出尺寸
size_t actualOutSize = 0;
//执行CCCrypt加密解密方法
//operation指的是加密解密的类型
//我们传入的指针变量contentBytes实际上对应的是存储区的地址,当然我们要在加密方法中,在地址中放入密文块或者名文块,方便后期获取
//把actualOutSize的地址放到函数内,在函数中对地址中对应的数字进行操作,最后我们得到的是输出时候的长度
CCCryptorStatus cryptStatus = CCCrypt(operation,
kCCAlgorithmAES128,
0x0000,
keyPtr,
kCodeKeySize,
iv,
contentBytes,
dataLength,
operationBytes,
operationSize,
&actualOutSize);
//如果判断状态是成功的话
if (cryptStatus == kCCSuccess) {
//从一个给定的给定字节数的存储区地址,创建并返回一个数据对象。从存储区地址获取存储区内容,内容在方法中已经放好了 operationBytes本身是一个地址
return [NSData dataWithBytesNoCopy:operationBytes length:actualOutSize];
}
//malloc()函数自动分配内存,最后是一定要释放的
free(operationBytes);
operationBytes = NULL;
return nil;
}