【发布时间】:2012-11-30 02:58:48
【问题描述】:
我正在使用以下代码进行文件加密和解密,
- (NSData *) AESEncrypt:(NSString *)key withData:(NSData *)fileData {
// 'key' should be 32 bytes for AES256, will be null-padded otherwise
char keyPtr[kCCKeySizeAES256+1]; // room for terminator (unused)
bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)
// fetch key data
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [fileData 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 numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,keyPtr, kCCKeySizeAES256,
NULL /* initialization vector (optional) */,
[fileData 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 *) AESDecrypt:(NSString *)key withData:(NSData *)fileData {
// 'key' should be 32 bytes for AES256, will be null-padded otherwise
char keyPtr[kCCKeySizeAES256+1]; // room for terminator (unused)
bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)
// fetch key data
//[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [fileData 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, kCCKeySizeAES256, NULL /* initialization vector (optional) */,
[fileData 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;
}
效果很好。但看起来它正在使用 AES256 ,但我想将其更改为 AES128 所以我将第一行从 char keyPtr[kCCKeySizeAES256+1]; 更改为 char keyPtr[kCCKeySizeAES128+1]; 。
Fi 我改了,只有加密有效。解密无法正常工作。谁能告诉我为什么?
【问题讨论】:
-
请贴出你修改过的代码,而不是原代码。请注意,块大小在 128 位和 256 位之间是相同的,因此您可以保留
kCCBlockSizeAES128。 -
@DuncanJones 我也更改了 BlockSize。加密正在发生所有情况。只有解密失败。虽然解密将 CCCryptorStatus 作为 kCCDecodeError。
-
投票否决并结束,因为您没有回应邓肯的评论,这使得这个问题无法回答。
标签: iphone ios security encryption aes