我们在传递敏感数据是,需要对data进行加密。我们采用高AES 128位加密。加密模式采用CBC,填充模式采用PKCS5Padding方式。
+(NSString*)AES128Encrypt:(NSString*)plainText
{
char keyPtr[kCCKeySizeAES128+1];
memset(keyPtr,0,sizeof(keyPtr));
[gkey getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
char ivPtr[kCCBlockSizeAES128+1];
memset(ivPtr,0,sizeof(ivPtr));
[gIv getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSUTF8StringEncoding];
NSData* data = [plainText dataUsingEncoding:NSUTF8StringEncoding];
NSIntegerdataLength = [datalength];
NSInteger diff = kCCKeySizeAES128 - (dataLength % kCCKeySizeAES128);
NSIntegernewSize =0;
if(diff >0)
{
newSize = dataLength + diff;
}
chardataPtr[newSize];
memcpy(dataPtr, [databytes], [datalength]);
for(inti =0; i < diff; i++)
{
dataPtr[i + dataLength] =0x00;
}
size_tbufferSize = newSize +kCCBlockSizeAES128;
void*buffer =malloc(bufferSize);
memset(buffer,0, bufferSize);
size_tnumBytesCrypted =0;
CCCryptorStatuscryptStatus =CCCrypt(kCCEncrypt,
kCCAlgorithmAES128,
0x0000|kCCOptionPKCS7Padding, //PKCS7Padding
keyPtr,
kCCKeySizeAES128,
ivPtr,
dataPtr,
sizeof(dataPtr),
buffer,
bufferSize,
&numBytesCrypted);
if(cryptStatus ==kCCSuccess) {
NSData*resultData = [NSDatadataWithBytesNoCopy:bufferlength:numBytesCrypted];
return[GTMBase64stringByEncodingData:resultData];
}
free(buffer);
return nil;
}
+(NSString*)AES128Decrypt:(NSString*)encryptText
{
charkeyPtr[kCCKeySizeAES128+1];
memset(keyPtr,0,sizeof(keyPtr));
[gkey getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
char ivPtr[kCCBlockSizeAES128 + 1];
memset(ivPtr,0,sizeof(ivPtr));
[gIv getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSUTF8StringEncoding];
NSData *data = [GTMBase64 decodeData:[encryptText dataUsingEncoding:NSUTF8StringEncoding]];
NSUIntegerdataLength = [datalength];
size_tbufferSize = dataLength +kCCBlockSizeAES128;
void*buffer =malloc(bufferSize);
size_tnumBytesCrypted =0;
CCCryptorStatuscryptStatus =CCCrypt(kCCDecrypt,
kCCAlgorithmAES128,
0x0000|kCCOptionPKCS7Padding,
keyPtr,
kCCBlockSizeAES128,
ivPtr,
[databytes],
dataLength,
buffer,
bufferSize,
&numBytesCrypted);
if(cryptStatus ==kCCSuccess) {
NSData*resultData = [NSDatadataWithBytesNoCopy:bufferlength:numBytesCrypted];
return [[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding];
}
free(buffer);
return nil;
}
以上为加密和解密的方法。其中gkey和gIv为秘钥和偏移量。