AES加密有四种工作模式:ECB、CBC、CFB和OFB,其中IOS支持ECB(kCCOptionPKCS7Padding 对应Java中的kCCOptionPKCS5Padding)和CBC(kCCOptionECBMode)
AES是开发中常用的加密算法之一。然而由于前后端开发使用的语言不统一,导致经常出现前端加密而后端不能解密的情况出现。然而无论什么语言系统,AES的算法总是相同的, 因此导致结果不一致的原因在于 加密设置的参数不一致 。于是先来看看在两个平台使用AES加密时需要统一的几个参数。
密钥长度(Key Size)
加密模式(Cipher Mode)
填充方式(Padding)
初始向量(Initialization Vector)
与服务器通讯的时候,除了确定密钥外,加密模式和填充方式也要确定。第一个例子中,就是使用了kCCOptionPKCS7Padding加密模式,并且有IV(初始向量),而第二个例子中使用了ECB(没有补码方式)。
此外也要注意转码后的密文是转成16进制,还是base64编码。
//
// AES128Util.m
// NxControl
//
// Created by zxy on 2018/3/30.
// Copyright © 2018年 zxy. All rights reserved.
//
#import "AES128Util.h"
#import <CommonCrypto/CommonCryptor.h>
@implementation AES128Util
+(NSString *)AES128Encrypt:(NSString *)plainText key:(NSString *)key
{
char keyPtr[kCCKeySizeAES128+1];
memset(keyPtr, 0, sizeof(keyPtr));
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
NSData* data = [plainText dataUsingEncoding:NSUTF8StringEncoding];
NSUInteger dataLength = [data length];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
kCCAlgorithmAES128,
kCCOptionPKCS7Padding|kCCOptionECBMode, //ECB模式
keyPtr,
kCCBlockSizeAES128,
NULL, //没有补码
[data bytes],
dataLength,
buffer,
bufferSize,
&numBytesEncrypted);
if (cryptStatus == kCCSuccess) {
NSData *resultData = [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
//return [GTMBase64 stringByEncodingData:resultData];
return [self hexStringFromData:resultData];
}
free(buffer);
return nil;
}
+(NSString *)AES128Decrypt:(NSString *)encryptText key:(NSString *)key
{
char keyPtr[kCCKeySizeAES128 + 1];
memset(keyPtr, 0, sizeof(keyPtr));
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
//NSData *data = [GTMBase64 decodeData:[encryptText dataUsingEncoding:NSUTF8StringEncoding]];
NSData *data=[self dataForHexString:encryptText];
NSUInteger dataLength = [data length];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
size_t numBytesCrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,
kCCAlgorithmAES128,
kCCOptionPKCS7Padding|kCCOptionECBMode,
keyPtr,
kCCBlockSizeAES128,
NULL,
[data bytes],
dataLength,
buffer,
bufferSize,
&numBytesCrypted);
if (cryptStatus == kCCSuccess) {
NSData *resultData = [NSData dataWithBytesNoCopy:buffer length:numBytesCrypted];
return [[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding];
}
free(buffer);
return nil;
}
NSString const *kInitVector2 = @"0102030405060708";
size_t const kKeySize2 = kCCKeySizeAES128;
//size_t const kKeySize = kCCKeySizeAES256;
+ (NSData *)cipherOperationWithcontenDate:(NSData *)contentData key:(NSData *)keyData operation:(CCOperation)operation {
NSUInteger dataLength = contentData.length;
void const *initVectorBytes = [kInitVector2 dataUsingEncoding:NSUTF8StringEncoding].bytes;
void const *contentBytes = contentData.bytes;
void const *keyBytes = keyData.bytes;
size_t operationSize = dataLength + kCCBlockSizeAES128;
void *operationBytes = malloc(operationSize);
if (operationBytes == NULL) {
return nil;
}
size_t actualOutSize = 0;
CCCryptorStatus cryptStatus = CCCrypt(operation,
kCCAlgorithmAES,
kCCOptionPKCS7Padding,
keyBytes,
kKeySize2,
initVectorBytes,
contentBytes,
dataLength,
operationBytes,
operationSize,
&actualOutSize);
if (cryptStatus == kCCSuccess) {
return [NSData dataWithBytesNoCopy:operationBytes length:actualOutSize];
}
free(operationBytes);
operationBytes = NULL;
return nil;
}
+(NSString *)aesEncryptStringWithContent:(NSString *)content key:(NSString *)key {
NSCParameterAssert(content);
NSCParameterAssert(key);
NSData *contentData = [content dataUsingEncoding:NSUTF8StringEncoding];
NSData *keyData = [key dataUsingEncoding:NSUTF8StringEncoding];
NSData *encrptedData = [self aesEncryptData:contentData keyData:keyData];
return [self hexStringFromData:encrptedData];
// [encrptedData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
}
+ (NSString *)aesDecryptStringWithContent:(NSString *)content key:(NSString *)key {
NSCParameterAssert(content);
NSCParameterAssert(key);
NSData *contentData = [self dataForHexString:content];
// [[NSData alloc] initWithBase64EncodedString:content options:NSDataBase64DecodingIgnoreUnknownCharacters];
NSData *keyData = [key dataUsingEncoding:NSUTF8StringEncoding];
NSData *decryptedData = [self aesDecryptData:contentData keyData:keyData];
return [[NSString alloc] initWithData:decryptedData encoding:NSUTF8StringEncoding];
}
+(NSData *)aesEncryptData:(NSData *)contentData keyData:(NSData *)keyData {
NSCParameterAssert(contentData);
NSCParameterAssert(keyData);
NSString *hint = [NSString stringWithFormat:@"The key size of AES-%lu should be %lu bytes!", kKeySize2 * 8, kKeySize2];
NSCAssert(keyData.length == kKeySize2, hint);
return [self cipherOperationWithcontenDate:contentData key:keyData operation:kCCEncrypt];
}
+(NSData *)aesDecryptData:(NSData *)contentData keyData:(NSData *)keyData {
NSCParameterAssert(contentData);
NSCParameterAssert(keyData);
NSString *hint = [NSString stringWithFormat:@"The key size of AES-%lu should be %lu bytes!", kKeySize2 * 8, kKeySize2];
NSCAssert(keyData.length == kKeySize2, hint);
return [self cipherOperationWithcontenDate:contentData key:keyData operation:kCCDecrypt];
}
// 普通字符串转换为十六进
+ (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
网友评论