一、AES加密模式有好幾種,網上大可能是CBC、256模式,找了很久才找到解決ECB128模式加密。加密
AES須要導入頭文件spa
#import <CommonCrypto/CommonCryptor.h>code
#import "GTMBase64.h" //加密後的數據在Base64轉字符串類型blog
+(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]; return [GTMBase64 stringByEncodingData:resultData]; } free(buffer); return nil; }
直接放 Demo: AES/ECB模式128Demo下載 密碼:qj57字符串