AES加密 java后台使用byte[]字符集 加密 iOS端处
NSString const *key = @"2345432134564324565432345"; //加密字符串
size_t const kKeySize = kCCKeySizeAES128; //加密位数
NSData * cipherOperation(NSData *contentData, CCOperation operation) {
NSUInteger dataLength = contentData.length;
void const *contentBytes = contentData.bytes;
const char *cStr = [key UTF8String];
unsigned char result[16];
CC_MD5( cStr, (CC_LONG)strlen(cStr), result );
void const *keyBytes = result;
size_t operationSize = dataLength + kCCBlockSizeAES128;
void *operationBytes = malloc(operationSize);
if (operationBytes == NULL) {
return nil;
}
size_t actualOutSize = 0;
CCCryptorStatus cryptStatus = CCCrypt(operation,
kCCAlgorithmAES,
kCCOptionPKCS7Padding|kCCOptionECBMode,
keyBytes,
kKeySize,
NULL,
contentBytes,
dataLength,
operationBytes,
operationSize,
&actualOutSize);
if (cryptStatus == kCCSuccess) {
return [NSData dataWithBytesNoCopy:operationBytes length:actualOutSize];
}
free(operationBytes);
operationBytes = NULL;
return nil;
}
加密
NSString* aesEncryptString(NSString*content) {
NSCParameterAssert(content);
NSData *contentData = [content dataUsingEncoding:NSUTF8StringEncoding];
NSData*encrptedData =cipherOperation(contentData,kCCEncrypt);;
return[AESCipherhexStringFromData:encrptedData];
}
解密
NSString* aesDecryptString(NSString*content) {
NSCParameterAssert(content);
NSData*contentData = [AESCipherconvertHexStrToData:content];
NSData*decryptedData =cipherOperation(contentData, kCCDecrypt);
return [[NSString alloc] initWithData:decryptedData encoding:NSUTF8StringEncoding];
}
// 普通字符串转换为十六进
+(NSString*)hexStringFromData:(NSData*)data {
Byte*bytes = (Byte*)[databytes];
// 下面是Byte 转换为16进制。
NSString*hexStr =@"";
for(inti=0; i<[datalength]; i++) {
NSString*newHexStr = [NSStringstringWithFormat:@"%x",bytes[i] &0xff];//16进制数
newHexStr = [newHexStruppercaseString];
if([newHexStrlength] ==1) {
newHexStr = [NSStringstringWithFormat:@"0%@",newHexStr];
}
hexStr = [hexStrstringByAppendingString:newHexStr];
}
return hexStr.lowercaseString;
}
// 16进制转NSData
+ (NSData*)convertHexStrToData:(NSString*)str{
if(!str || [strlength] ==0) {
returnnil;
}
NSMutableData *hexData = [[NSMutableData alloc] initWithCapacity:20];
NSRangerange;
if([strlength] %2==0) {
range =NSMakeRange(0,2);
}else{
range =NSMakeRange(0,1);
}
for(NSIntegeri = range.location; i < [strlength]; i +=2) {
unsignedintanInt;
NSString*hexCharStr = [strsubstringWithRange:range];
NSScanner*scanner = [[NSScanneralloc]initWithString:hexCharStr];
[scannerscanHexInt:&anInt];
NSData*entity = [[NSDataalloc]initWithBytes:&anIntlength:1];
[hexDataappendData:entity];
range.location+= range.length;
range.length=2;
}
returnhexData;
}