iOS之AES加密解密

Posted applejun

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了iOS之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加密解密的主要内容,如果未能解决你的问题,请参考以下文章

iOS开发之Objective-c的AES加密和解密算法的实现

AES算法加密解密工具类util之改进之动态AES密钥加密

iOS逆向之对称算法(下)

IOS AES加密

iOS AES加密

iOS AES的加密解密