ios AES256解密方法
2024-08-28 本文已影响0人
天上飞的狒狒
1 首先创建一个NSString分类
这是.h文件
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface NSString (EncryptVerbHandle)
/**
AES解密算法
@param str 要解密的字符串
@param keyStr: 解码key(需要和后台协商定义)
@return 解密后的字符串
*/
+ (NSString *) aes256_decrypt:(NSString *) str andkey:(NSString *)keyStr;
@end
NS_ASSUME_NONNULL_END
2 这是.m文件
#import "NSString+EncryptVerbHandle.h" //AES256加密
@implementation NSString (EncryptVerbHandle)
// Aes解密
+ (NSString *)aes256_decrypt:(NSString *)str andkey:(NSString *)keyStr{
//先对加密的字符串进行base64解码
NSData *keyData = [[NSData alloc] initWithBase64EncodedString:str options:0];
char keyPtr[kCCKeySizeAES256 + 1];
bzero(keyPtr, sizeof(keyPtr));
/*AES加密与解密的秘钥,需要与后台协商共同定义,保持与后台的秘钥相同*/
[keyStr getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [keyData length];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void* buffer = malloc(bufferSize);
size_t numBytesDecrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,
kCCAlgorithmAES128,
kCCOptionPKCS7Padding|kCCOptionECBMode,
keyPtr,
kCCKeySizeAES256,
NULL /* initialization vector (optional) */,
[keyData bytes],
dataLength, /* input */
buffer,
bufferSize, /* output */
&numBytesDecrypted);
if (cryptStatus == kCCSuccess) {
NSData *data = [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
return result;
}else{
free(buffer);
return nil;
}
}
@end
3 调用
先引入 #import "NSString+EncryptVerbHandle.h" //AES解密
NSString *mb256Str = [NSString aes256_decrypt:@"xxx" andkey:@"xxx"];
//mb256Str就是解码完的参数
要注意这几个参数,参数不同,解密的规则不同
kCCAlgorithmAES128
kCCKeySizeAES256