我有一些問題解密在bash中用openssl加密的文件。以下是我一步一步做的事情。我無法弄清楚它出錯的地方。如何在CLI中加密文件並使用iOS解密?
原始文件(新行結束):
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.
如何添加PKCS7填充到我的加密?我嘗試了用kCCOptionECBMode替換kCCOptionPKCS7Padding,cryptStatus現在是「成功」,但返回的結果沒有正確解密。 – maxagaz
你會得到什麼?如果它是正確的文本,並在最後添加字節,則添加的字節是填充並可以安全地刪除。 – rossum
我得到一個非人類可讀的文本:即使我更改密碼的任何其他內容也總是相同,如果我通過NSASCIIStringEncoding更改NSUTF8StringEncoding,也是如此。 – maxagaz