IOS 使用AES/ECB/PKCS7Padding 加密、解密数据 |
AESCrypt-ObjC-master - Github:
https://github.com/Gurpartap/aescrypt
|
+ (NSData*)base64DataFromString:(NSString*)string;
+ (NSString*)base64StringFromData:(NSData*)data length:(NSUInteger)length;
|
NSData*cipher = [XNFunctionconvertHexStrToData:content];
//方法如下(注意:这里的十六进制是指十六进制字符串,不是0x000002)
//十六进制转换为NSData
+ (NSData*)convertHexStrToData:(NSString*)str { if (!str || [str length] ==0) { return nil; } NSMutableData *hexData = [[NSMutableDataalloc]initWithCapacity:8]; NSRange range; if ([str length] %2==0) { range = NSMakeRange(0,2); } else { range = NSMakeRange(0,1); } for (NSIntegeri = range.location; i < [str length]; i +=2) { unsigned int anInt; NSString *hexCharStr = [str substringWithRange:range]; NSScanner *scanner = [[NSScanneralloc]initWithString:hexCharStr]; [scanner scanHexInt:&anInt]; NSData *entity = [[NSDataalloc]initWithBytes:&anIntlength:1]; [hexData appendData:entity]; range.location+= range.length; range.length=2;
}
NSLog(@"hexdata: %@", hexData);
return hexData; } //NSData转换为16进制 + (NSString*)convertDataToHexStr:(NSData*)data { if (!data || [data length] ==0) { return @""; } NSMutableString *string = [[NSMutableStringalloc]initWithCapacity:[datalength]]; [data enumerateByteRangesUsingBlock:^(constvoid*bytes,NSRangebyteRange,BOOL*stop) { unsigned char *dataBytes = (unsignedchar*)bytes; for (NSIntegeri =0; i < byteRange.length; i++) { NSString *hexStr = [NSStringstringWithFormat:@"%x", (dataBytes[i]) & 0xff]; if ([hexStr length] ==2) { [string appendString:hexStr]; } else { [string appendFormat:@"0%@", hexStr]; } } }]; return string;
}
|
NSString*str =@"ABC123!@#中文";
NSString*key =@"F8hfdtgfu**0Ka0";
NSData*password = [[keydataUsingEncoding:NSUTF8StringEncoding]MD5Sum];
CCCryptorStatusstatus =kCCSuccess;
NSData*data = [strdataUsingEncoding:NSUTF8StringEncoding];
//加密
NSData* result = [data dataEncryptedUsingAlgorithm:kCCAlgorithmAES128
key:password
options:kCCOptionPKCS7Padding|kCCOptionECBMode
error:&status];
//解密:
NSData*encrypted = [resultdecryptedDataUsingAlgorithm:kCCAlgorithmAES128
key:password //字符串key够16位,可以直接传进去,不用转成NSdata也行
options:kCCOptionPKCS7Padding|kCCOptionECBMode
error:&status];
plainString = [[NSStringalloc]initWithData:encryptedencoding:NSUTF8StringEncoding];
NSLog(@"%@", plainString); //输出:ABC123!@#中文
|
NSString*plainString =nil;
NSString*key =@"%F8hfdtgfu**0Ka0";
CCCryptorStatusstatus =kCCSuccess;
//十六进制字符串 -> NSData
NSData*data = [selfconvertHexStrToData:text];
//解密:
NSData*encrypted = [datadecryptedDataUsingAlgorithm:kCCAlgorithmAES128
key:key
options:kCCOptionPKCS7Padding|kCCOptionECBMode
error:&status];
plainString = [selfconvertDataToHexStr:encrypted]; //转出成功,但看起来还是十六进制字符串,于是进行下步
plainString = [selfstringFromHexString:plainString];//十六进制字符串转成普通字符串
NSLog(@"%@", plainString); //失败
+ (NSString*)stringFromHexString:(NSString*)hexString { //
char*myBuffer = (char*)malloc((int)[hexStringlength] /2+1);
bzero(myBuffer, [hexStringlength] /2+1); for (inti =0; i < [hexStringlength] -1; i +=2) { unsigned int anInt; NSString * hexCharStr = [hexString substringWithRange:NSMakeRange(i,2)]; NSScanner * scanner = [[NSScanneralloc]initWithString:hexCharStr]; [scanner scanHexInt:&anInt]; myBuffer[i / 2] = (char)anInt; } NSString *unicodeString = [NSStringstringWithCString:myBufferencoding:4]; NSLog(@"字符串:%@",unicodeString);
return unicodeString;
}
|
//16位的key,补位操作省略
NSString*key =@"F8hfdtgfu**0Ka0";
//HexString -> NSData
NSData*cipher = [selfconvertHexStrToData:text];
//解密
NSData*plain = [cipherAES256DecryptWithKey:key];
//直接是用UTF-8编码转出
NSString*plainString = [[NSStringalloc]initWithData:plainencoding:NSUTF8StringEncoding];
NSLog(@"[解密结果] :%@", plainString); //解密成功
|
/*创建 cryptor
* 参数1:解密 * 参数2:填充方式,这里传入kCCAlgorithmAES128 * 参数3:工作模式:kCCOptionPKCS7Padding | kCCOptionECBMode * 参数4:key * 参数5:key的长度 * 参数6:iv
*参数7:CCCryptorRef cryptor = NULL;
*/
CCCryptorCreate(kCCEncrypt, algorithm, options, [keyDatabytes], [keyDatalength], [ivDatabytes], &cryptor );
NSData* resultData = [self_runCryptor: cryptorresult: &status];
|
- (NSData*) _runCryptor: (CCCryptorRef) cryptor result: (CCCryptorStatus*) status {
size_tbufsize = CCCryptorGetOutputLength( cryptor, (size_t)[selflength],true );
void* buf =malloc( bufsize );
size_tbufused = 0;
size_tbytesTotal = 0;
/*更新 cryptor
*参数1:cryptor
*参数2:密文
*参数3:密文大小
*参数4:buf
*参数5:bufsize
*参数6:...
*/
*status =CCCryptorUpdate( cryptor, [selfbytes], (size_t)[selflength],buf, bufsize, &bufused );
if( *status !=kCCSuccess) {
free( buf );
return( nil );
}
bytesTotal += bufused;
// From Brent Royal-Gordon (Twitter: architechies):
// Need to update buf ptr past used bytes when calling CCCryptorFinal()
*status =CCCryptorFinal( cryptor, buf + bufused, bufsize - bufused, &bufused );
if( *status != kCCSuccess ) {
free( buf );
return( nil );
}
bytesTotal += bufused;
return( [NSDatadataWithBytesNoCopy: buflength: bytesTotal] );
}
|
- (NSData*)AES256DecryptWithKey:(NSString*)key //解密
{
//AES的密钥长度有128字节、192字节、256字节几种,这里举出可能存在的最大长度
charkeyPtr[kCCKeySizeAES256+1];
bzero(keyPtr,sizeof(keyPtr));
[keygetCString:keyPtrmaxLength:sizeof(keyPtr)encoding:NSUTF8StringEncoding];
//密文的长度
NSUIntegerdataLength = [selflength];
//密文长度+补位长度
size_tbufferSize = dataLength +kCCBlockSizeAES128;
//为解密结果开辟空间
void*buffer =malloc(bufferSize);
size_t numBytesDecrypted = 0;
/* kCCDecrypt:解密
* kCCAlgorithmAES128:加密方式
* kCCOptionPKCS7Padding | kCCOptionECBMode:工作模式
* keyPtr:UTF-8格式的key
* kCCBlockSizeAES128:按16位长度解密
* iv:AES不用iv
* [self bayes]:密文
* ...
*/
CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,kCCAlgorithmAES128,
kCCOptionPKCS7Padding|kCCOptionECBMode,
keyPtr, kCCBlockSizeAES128, NULL, [selfbytes], dataLength, buffer, bufferSize, &numBytesDecrypted); if (cryptStatus == kCCSuccess) { return [NSDatadataWithBytesNoCopy:bufferlength:numBytesDecrypted]; } free(buffer); return nil;
}
|