IOS AES加密/解密

对数据进行操作处理过程中,需要对数据进行加密/解密处理,存在各种各样的加密方式,此处介绍AES对称加密/解密。

AES加密/解密过程结合了Base64编码/解密,利用唯一秘钥key(AES具体描述此处不作详细介绍),导入如下库文件:

#import 
#import 

AES加密/解密过程,必须保证其秘钥key一致,否则会导致解密过程失败。

AESUtil.h

#import 
#import 
#import 

/**
 * AES工具类
 */
@interface AESUtil : NSObject

/**
 * AES加密
 */
+ (NSString *)aesEncrypt:(NSString *)sourceStr;

/**
 * AES解密
 */
+ (NSString *)aesDecrypt:(NSString *)secretStr;

@end

AESUtil.m

#import 
#import "AESUtil.h"

@interface AESUtil()

@end

// 秘钥key
const NSString *AESKey = @"abcdefghABCDEFGH";

@implementation AESUtil

+ (NSString *)aesEncrypt:(NSString *)sourceStr{
    if (!sourceStr) {
        return nil;
    }
    char keyPtr[kCCKeySizeAES256 + 1];
    bzero(keyPtr, sizeof(keyPtr));
    [AESKey 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 *)aesDecrypt:(NSString *)secretStr{
    if (!secretStr) {
        return nil;
    }
    //先对加密的字符串进行base64解码
    NSData *decodeData = [[NSData alloc] initWithBase64EncodedString:secretStr options:NSDataBase64DecodingIgnoreUnknownCharacters];
     
    char keyPtr[kCCKeySizeAES256 + 1];
    bzero(keyPtr, sizeof(keyPtr));
    [AESKey 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

注:秘钥key size不超过16字节。

你可能感兴趣的:(IOS,AES,加密,解密,C/C++)