我在 bash 中解密用 openssl 加密的文件时遇到了一些问题。下面是我一步一步做的。我不知道哪里出了问题。
原始文件(以换行符结尾):
123456
abcdef
ghijkl
生成 32 字节长的随机密码:
$ openssl rand -hex 32
fec8950708098e9075e8b4df9a969aa7963c4d820158e965c7848dbfc8ca73ed
加密文件:
$ openssl aes-128-ecb -in original.txt -out encrypted.txt
关于加密文件:
$ file encrypted.txt
encrypted.txt: Non-ISO extended-ASCII text, with CR line terminators, with overstriking
$ cat encrypted.txt
Salted__??\z?F?z????4G}Q? Y?{ӌ???????b*??
调用解密方法的代码:
NSData *myDataDec = [self aesDecrypt:@"fec8950708098e9075e8b4df9a969aa7963c4d820158e965c7848dbfc8ca73ed" data:myData];
NSLog(@"decrypted: %@", [[NSString alloc] initWithData:myDataDec encoding:NSASCIIStringEncoding]);
解密方法:
- (NSData *)aesDecrypt:(NSString *)key data:(NSData *)data
{
// '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 = [data 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(kCCDecrypt,
kCCAlgorithmAES128,
kCCOptionPKCS7Padding,
keyPtr,
kCCKeySizeAES256,
NULL /* initialization vector (optional) */,
[data bytes],
dataLength, /* input */
buffer,
bufferSize, /* output */
&numBytesEncrypted);
NSLog(@"cryptStatus: %d", cryptStatus);
if (cryptStatus == kCCSuccess)
{
NSLog(@"aes success");
//the returned NSData takes ownership of the buffer and will free it on deallocation
return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
}
NSLog(@"aes error");
free(buffer); //free the buffer;
return nil;
}
日志:
2012-09-01 15:08:51.331 My Project[75582:f803] cryptStatus: -4304
2012-09-01 15:08:51.332 My Project[75582:f803] aes error
2012-09-01 15:08:51.332 My Project[75582:f803] decrypted:
kCCDecodeError 详细信息:
kCCDecodeError - Input data did not decode or decrypt properly.