码迷,mamicode.com
首页 > 移动开发 > 详细

iOS之AES加密解密

时间:2019-06-19 12:09:42      阅读:561      评论:0      收藏:0      [点我收藏+]

标签:ecb   ttext   ret   ini   rac   dig   nsdata   ptr   aes加密   

//AES加密解密
#import <CommonCrypto/CommonCrypto.h>
#import <CommonCrypto/CommonDigest.h>

//AES128位加密
base64编码 注:kCCKeySizeAES128点进去可以更换256位加密 -(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) { NSData *resultData = [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted]; NSString *stringBase64 = [resultData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed]; // base64格式的字符串 return stringBase64; } 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];//base64解码 NSUInteger dataLength = [data length]; size_t bufferSize = dataLength + kCCBlockSizeAES128; void *buffer = malloc(bufferSize); size_t numBytesCrypted = 0; CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding|kCCOptionECBMode, keyPtr, kCCBlockSizeAES128, NULL, [data bytes], dataLength, buffer, bufferSize, &numBytesCrypted); if (cryptStatus == kCCSuccess) { NSData *resultData = [NSData dataWithBytesNoCopy:buffer length:numBytesCrypted]; return [[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding]; } free(buffer); return nil; }

 

iOS之AES加密解密

标签:ecb   ttext   ret   ini   rac   dig   nsdata   ptr   aes加密   

原文地址:https://www.cnblogs.com/appleJun/p/11050414.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!