我在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*??调用decrypt方法的代码:
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.发布于 2012-09-03 08:16:55
OpenSSL使用非标准格式。AESencrypt非常糟糕(而且不安全)。把它们放在一起,这是行不通的。有关iOS上的OpenSSL兼容解决方案,请参阅RNCryptor。OpenSSL本身有很多问题,但它是我现在能推荐的最好的命令行选项。
发布于 2012-09-01 18:28:39
加密文件时,您似乎没有添加填充。您似乎希望在解密时使用PKCS7填充。解密方法将自动检查正确的填充。如果它发现不正确的填充,那么它将抛出错误。
将PKCS7填充添加到加密方法中,看看会发生什么。
还要注意的是,ECB不是一种安全模式。首选使用CBC或CTR模式。如果您需要身份验证和加密,请使用GCM模式。
https://stackoverflow.com/questions/12225640
复制相似问题