AES256加解密

AES256加解密,第1张

本地有个plist文件,需要对里面的几个字段加密,刚开始用的base64加密的,老大说太简单,网上搜罗了一下,觉得这个加密法挺合适: 
AES:高级加密标准(Advanced Encryption Standard)

    加密步骤: 字符串经过AES加密得到NSData类型数据,然后在对加密后的NSData数据进行Base64转码,得出最终的字符串

    解密步骤: 对要解密的字符串进行Base64解码得到NSData类型数据,然后对NSData数据经过AES解密,得出原字符串

//创建一个基于NSObject的AESUtility类
#import 
 
@interface AESUtility : NSObject
+ (NSString *)EncryptString:(NSString *)sourceStr;
+ (NSString *)DecryptString:(NSString *)secretStr;
@end
#import "AESUtility.h"
 
#import 
#import 
 
//加密与解密的秘钥,保持与后台的秘钥相同
static NSString *key = @"12345678";
 
@implementation AESUtility
 
+ (NSString *)EncryptString:(NSString *)sourceStr
{
    char keyPtr[kCCKeySizeAES256 + 1];
    bzero(keyPtr, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
     
    NSData *sourceData = [sourceStr dataUsingEncoding:NSUTF8StringEncoding];
    NSUInteger dataLength = [sourceData length];
    size_t buffersize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(buffersize);
    size_t numBytesEncrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding | kCCOptionECBMode, keyPtr, kCCBlockSizeAES128, NULL, [sourceData bytes], dataLength, buffer, buffersize, &numBytesEncrypted);
     
    if (cryptStatus == kCCSuccess) {
        NSData *encryptData = [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
        //对加密后的二进制数据进行base64转码
        return [encryptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
    }
    else
    {
        free(buffer);
        return nil;
    }
}
 
+ (NSString *)DecryptString:(NSString *)secretStr
{
    //先对加密的字符串进行base64解码
    NSData *decodeData = [[NSData alloc] initWithBase64EncodedString:secretStr options:NSDataBase64DecodingIgnoreUnknownCharacters];
     
    char keyPtr[kCCKeySizeAES256 + 1];
    bzero(keyPtr, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
     
    NSUInteger dataLength = [decodeData length];
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    size_t numBytesDecrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding | kCCOptionECBMode, keyPtr, kCCBlockSizeAES128, NULL, [decodeData bytes], dataLength, buffer, bufferSize, &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
注意点:
    1. 加密与解密的秘钥key,需要与后台协商共同定义,保持与后台的秘钥相同,也可以通过接口从后台获得;
    2. 导入头文件:#import 和#import 

来自:参考链接

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/996670.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存