AES加密是对称加密的一种,全称是Advanced Encryption Standard(高级加密标准)。常用于网络传输中的数据加解密。
//
// NSData+AESEncryption.h
// ownloadData
//
// Created by CZ on 2023/7/25.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface NSData (AESEncryption)
- (NSData *)AES128ParmEncryptWithKey:(NSString *)key iv:(NSString *)iv;
- (NSData *)AES128ParmDecryptWithKey:(NSString *)key iv:(NSString *)iv;
@end
NS_ASSUME_NONNULL_END
//
// NSData+AESEncryption.m
// ownloadData
//
// Created by 陈镇 on 2023/7/25.
//
#import <CommonCrypto/CommonCryptor.h>
#import "NSData+AESEncryption.h"
@implementation NSData (AESEncryption)
- (NSData *)AES128ParmEncryptWithKey:(NSString *)key iv:(NSString *)iv
{
char keyPtr[kCCKeySizeAES128+1];
bzero(keyPtr, sizeof(keyPtr));
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
char ivPtr[kCCBlockSizeAES128 + 1];
bzero(ivPtr, sizeof(ivPtr));
[iv getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [self length];
size_t bufferSize = dataLength + kCCKeySizeAES128;
void *buffer = malloc(bufferSize);
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES,
kCCOptionPKCS7Padding,
keyPtr, kCCKeySizeAES128,
ivPtr,
[self bytes], dataLength,
buffer, bufferSize,
&numBytesEncrypted);
if (cryptStatus == kCCSuccess) {
return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
}
free(buffer);
return nil;
}
//解密
- (NSData *)AES128ParmDecryptWithKey:(NSString *)key iv:(NSString *)iv
{
char keyPtr[kCCKeySizeAES128 + 1];
bzero(keyPtr, sizeof(keyPtr));
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
char ivPtr[kCCBlockSizeAES128 + 1];
bzero(ivPtr, sizeof(ivPtr));
[iv getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [self length];
size_t bufferSize = dataLength + kCCKeySizeAES128;
void *buffer = malloc(bufferSize);
size_t numBytesDecrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,
kCCAlgorithmAES,
kCCOptionPKCS7Padding,
keyPtr,
kCCKeySizeAES128,
ivPtr,
[self bytes], dataLength,
buffer, bufferSize,
&numBytesDecrypted);
if (cryptStatus == kCCSuccess) {
NSData *t = [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
return t;
}
free(buffer);
return nil;
}
@end
使用
//base64字符串转data (text是待解析的base64字符串)
NSData *data = [[NSData alloc] initWithBase64EncodedString:text options:NSDataBase64DecodingIgnoreUnknownCharacters];
//aes解析
NSData *tttt = [data AES128ParmDecryptWithKey:key iv:iv];
//解析结果
NSString *str = [[NSString alloc] initWithData:tttt encoding:NSUTF8StringEncoding];
RTLog(@"---- %@",str);
参考文档
参考文档2