IOS AES ECB模式加密解密【拿走即用】

高级加密标准(英语:Advanced Encryption Standard,缩写:AES),在密码学中又称Rijndael加密法,是美国联邦政府采用的一种区块加密标准。


本次加密采用的是 128 ECB模式 PKCS7Padding 并转换16进制


根据自己的需求可自己调整 模式 ,base64格式还是 hex 格式(16进制)

AESUtil.h

#import 
#import 
#import 
 
/**
 * AES工具类
 */
@interface AESUtil : NSObject
 
/**
 * AES加密
 * AESKey
 */
+ (NSString *)AESencrypt:(NSDictionary *)dict;

/**
 * AES解密
 */
+ (NSString *)AESdecrypt:(NSDictionary *)dict;
 
@end

AESUtil.m

#import 
#import "AESUtil.h"
 
@interface AESUtil()
 
@end
 
// 秘钥key
//const NSString *AESKey = @"abcdefghABCDEFGH";
 
@implementation AESUtil
 
+ (NSString *)AESencrypt:(NSDictionary *)dict{
//+ (NSString *)AESencrypt:(NSString *)sourceStr AESKey: (NSString *) AESKey {
    NSString *sourceStr = [dict valueForKey:@"plain"];
    NSString *AESKey = [dict valueForKey:@"key"];
    
    if (!sourceStr) {
        return nil;
    }
    if (!AESKey) {
        AESKey = @"abcdefghABCDEFGH";
    }
    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];
        return [self hexStringFromData:encryptData];
    } else {
        free(buffer);
        return nil;
    }
}
 
//+ (NSString *)AESdecrypt:(NSString *)secretStr AESKey: (NSString *) AESKey{
+ (NSString *)AESdecrypt:(NSDictionary *)dict{
    NSString *secretStr = [dict valueForKey:@"plain"];
    NSString *AESKey = [dict valueForKey:@"key"];
    
    if (!secretStr) {
        return nil;
    }
    if (!AESKey) {
        AESKey = @"abcdefghABCDEFGH";
    }
//    //先对加密的字符串进行base64解码
//    NSData *decodeData = [[NSData alloc] initWithBase64EncodedString:secretStr options:NSDataBase64DecodingIgnoreUnknownCharacters];
    
    //16进制
    NSData *decodeData=[self dataForHexString:secretStr];
    
    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;
    }
}
 

// 普通字符串转换为十六进
+ (NSString *)hexStringFromData:(NSData *)data {
    Byte *bytes = (Byte *)[data bytes];
    // 下面是Byte 转换为16进制。
    NSString *hexStr = @"";
    for(int i=0; i<[data length]; i++) {
        NSString *newHexStr = [NSString stringWithFormat:@"%x",bytes[i] & 0xff]; //16进制数
        newHexStr = [newHexStr uppercaseString];
          
        if([newHexStr length] == 1) {
            newHexStr = [NSString stringWithFormat:@"0%@",newHexStr];
        }
          
        hexStr = [hexStr stringByAppendingString:newHexStr];
          
    }
    return hexStr;
}
  
//参考:http://blog.csdn.net/linux_zkf/article/details/17124577
//十六进制转Data
+ (NSData*)dataForHexString:(NSString*)hexString
{
    if (hexString == nil) {
        return nil;
    }
    const char* ch = [[hexString lowercaseString] cStringUsingEncoding:NSUTF8StringEncoding];
    NSMutableData* data = [NSMutableData data];
    while (*ch) {
        if (*ch == ' ') {
            continue;
        }
        char byte = 0;
        if ('0' <= *ch && *ch <= '9') {
            byte = *ch - '0';
        }else if ('a' <= *ch && *ch <= 'f') {
            byte = *ch - 'a' + 10;
        }else if ('A' <= *ch && *ch <= 'F') {
            byte = *ch - 'A' + 10;
        }
        ch++;
        byte = byte << 4;
        if (*ch) {
            if ('0' <= *ch && *ch <= '9') {
                byte += *ch - '0';
            } else if ('a' <= *ch && *ch <= 'f') {
                byte += *ch - 'a' + 10;
            }else if('A' <= *ch && *ch <= 'F'){
                byte += *ch - 'A' + 10;
            }
            ch++;
        }
        [data appendBytes:&byte length:1];
    }
    return data;
}

@end

测试调用【传入key(key:) 和 要加密的字符串(plain:)】
加密方法:AESencrypt
传入:字典 NSDictionary =》{key:abcdefghABCDEFGH,plain:"123"}
测试:传入key:abcdefghABCDEFGH plain:123

    NSDictionary *obj = @{@"key":@"abcdefghABCDEFGH",@"plain":@"123"};
    NSLog(@"%@",obj);
    NSString *str1=[AESUtil AESencrypt:obj];
    // 加密后的字符串
    NSLog(str1);

解密同理,可查看定义的方法 AESdecrypt

你可能感兴趣的:(IOS AES ECB模式加密解密【拿走即用】)