【发布时间】:2010-09-28 18:59:26
【问题描述】:
嗯,我试图用这种方法在扩展 NSData 的目标 c 中加密一个字符串:
@implementation NSData (AES128)
-
(NSData *)AES128Encrypt {
char keyPtr[kCCKeySizeAES128] = {'\xe1','\xaa','\x9c','\x61','\x46','\x74','\x44','\x56','\xf0','\xe5','\x47','\x46','\x86','\xdc','\x95','\x77'};
NSUInteger dataLength = [self length];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,kCCAlgorithmAES128,kCCOptionPKCS7Padding,keyPtr,kCCKeySizeAES128,NULL /* initialization vector (optional) /,[self bytes], dataLength, / input /buffer, bufferSize, / output */
&numBytesEncrypted);
if (cryptStatus == kCCSuccess) {
//the returned NSData takes ownership of the buffer and will free it on deallocation
return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
}
free(buffer); //free the buffer;
return nil;
}
-
(NSData *)AES128Decrypt {
char keyPtr[kCCKeySizeAES128] = {'\xe1','\xaa','\x9c','\x61','\x46','\x74','\x44','\x56','\xf0','\xe5','\x47','\x46','\x86','\xdc','\x95','\x77'};
NSUInteger dataLength = [self length];
//See the doc: For block ciphers, the output size will always be less than or
//equal to the input size plus the size of one block.
//That's why we need to add the size of one block here
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
size_t numBytesDecrypted = 0;
CCCryptorStatus cryptStatus=CCCrypt(kCCDecrypt,kCCAlgorithmAES128,kCCOptionPKCS7Padding,keyPtr, kCCKeySizeAES128,NULL /* initialization vector (optional) /,[self bytes], dataLength, / input /buffer, bufferSize, / output */&numBytesDecrypted);
if (cryptStatus == kCCSuccess) {
//the returned NSData takes ownership of the buffer and will free it on deallocation
return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
}
free(buffer); //free the buffer;
return nil;
}
@end
然后我在这里调用它:
NSString *strData = @"My string";
NSData *objNSData = [NSData dataWithData:[strData dataUsingEncoding: NSUTF8StringEncoding]];
NSLog(@"encrypted: %@",[objNSData description]);
如果我只是在目标 c 中使用它,它就可以正常工作。 但是当我尝试将它发送到 java 服务器时它不起作用。
我的密码数据如下所示:
86fcf0fa9e3dff93dc8918ffd02ee203 12de0bf8c8ba300456293c4240296c0d
如果我尝试在 java 中使用具有相同密钥的 AES 对其进行加密,我会得到:
86fcf0fa9e3dff93dc8918ffd02ee203 8388f173da143c6aeeb90e554259c83c
这很奇怪,因为前半部分是一样的。
有人知道为什么会这样吗? 谢谢。
【问题讨论】:
标签: java iphone objective-c encryption aes