我在 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:
kCCDecode错误详细信息:
kCCDecodeError - Input data did not decode or decrypt properly.
OpenSSL 使用非标准格式。 AES加密非常糟糕(而且不安全)。把它们放在一起,就行不通了。请参阅 RNCryptor 了解 iOS 上兼容 OpenSSL 的解决方案。 OpenSSL 本身有很多问题,但它是我现在可以推荐的最佳命令行选项。
加密文件时您似乎没有添加填充。解密时您似乎期望 PKCS7 填充。解密方法将自动检查填充是否正确。如果它发现不正确的填充,则会抛出错误。
将 PKCS7 填充添加到您的加密方法中,看看会发生什么。
另请注意,ECB 不是安全模式。优先使用 CBC 或 CTR 模式。如果您需要身份验证和加密,请使用 GCM 模式。
如何在线解密这个值?
U2FsdGVkX18ozWxI26cvk2+zHs8MMlDFXZM7LxVg+6c=