- (NSString *)AES256Encrypt:(NSString *)dataString WithKey:(NSString *)key iv:(NSString *)iv {
NSData *keyData = [key dataUsingEncoding:NSUTF8StringEncoding];
NSData *dataToEncrypt = [dataString dataUsingEncoding:NSUTF8StringEncoding];
NSData *ivData = [iv dataUsingEncoding:NSUTF8StringEncoding];
NSUInteger dataLength = [dataToEncrypt length];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
keyData.bytes, kCCKeySizeAES256,
ivData.bytes, // initialisation vector
dataToEncrypt.bytes,
dataToEncrypt.length, /* input */
buffer, bufferSize, /* output */
&numBytesEncrypted);
if (cryptStatus == kCCSuccess) {
//the returned NSData takes ownership of the buffer and will free it on deallocation
NSData *data = [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
return [[NSString alloc] initWithData:[GTMBase64 encodeData:data] encoding:NSUTF8StringEncoding];
}
free(buffer); //free the buffer;
return nil;
}
- (NSString *)AES256Decrypt:(NSString *)originString WithKey:(NSString *)key iv:(NSString *)iv {
NSData *originData = [originString dataUsingEncoding:NSUTF8StringEncoding];
NSData *cipherData = [GTMBase64 decodeData:originData];
NSData *keydata = [key dataUsingEncoding:NSUTF8StringEncoding];
NSData *dataToEncrypt = cipherData;
NSUInteger dataLength = [dataToEncrypt length];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
size_t numBytesDecrypted = 0;
NSData *ivData = [iv dataUsingEncoding:NSUTF8StringEncoding];
CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,
kCCAlgorithmAES128,
kCCOptionPKCS7Padding,
keydata.bytes,
kCCKeySizeAES256,
ivData.bytes,
[dataToEncrypt bytes],
[dataToEncrypt length],
buffer,
1024,
&numBytesDecrypted);
if (cryptStatus == kCCSuccess) {
NSData *data = [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}
free(buffer); //free the buffer;
return nil;
}
IOS使用Openssl aes256加密
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...