这次只展示代码,算法原理,网上一堆,我就不介绍了。
#import "Helper.h"#import#import #import "TDWBase64.h"@implementation Helper///加密+ (NSString *)aes256EncrytWithContent:(NSString *)content key:(NSString *)key { NSData *contentData = [content dataUsingEncoding:NSUTF8StringEncoding]; char keyptr[kCCKeySizeAES256+1]; bzero(keyptr, sizeof(keyptr)); [key getCString:keyptr maxLength:sizeof(keyptr) encoding:NSUTF8StringEncoding]; NSUInteger datalength = contentData.length; size_t bufferSize = datalength + kCCBlockSizeAES128; void *buffer = malloc(bufferSize); size_t numBytesEncrypted = 0; char iv[] = {0x30, 0x31, 0x30, 0x30, 0x31, 0x30, 0x30, 0x31, 0x30, 0x30, 0x31, 0x30, 0x30, 0x31, 0x30, 0x38}; CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding, keyptr, 32, iv, contentData.bytes, datalength, buffer, bufferSize, &numBytesEncrypted); if (cryptStatus == kCCSuccess) { NSData *data = [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted]; NSString *result = [TDWBase64 stringByEncodingData:data]; return result; } else { free(buffer); return nil; } return @"";}///解密+ (NSString *)aes256DecrytWithContent:(NSString *)content key:(NSString *)key { NSData *contentData = [TDWBase64 decodeString:content]; char keyptr[kCCKeySizeAES256+1]; bzero(keyptr, sizeof(keyptr)); [key getCString:keyptr maxLength:sizeof(keyptr) encoding:NSUTF8StringEncoding]; NSUInteger datalength = contentData.length; size_t bufferSize = datalength + kCCBlockSizeAES128; void *buffer = malloc(bufferSize); size_t numBytesEncrypted = 0; char iv[] = {0x30, 0x31, 0x30, 0x30, 0x31, 0x30, 0x30, 0x31, 0x30, 0x30, 0x31, 0x30, 0x30, 0x31, 0x30, 0x38}; CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding, keyptr, 32, iv, contentData.bytes, datalength, buffer, bufferSize, &numBytesEncrypted); if (cryptStatus == kCCSuccess) { NSData *data = [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted]; NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; return result; } else { free(buffer); return nil; } return @"";}复制代码
坑点: 1.
NSData *data = [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];复制代码
这个会自动释放buffer。 坑点文章:
2.Vi偏移量要用byte的形式写。