更新:找到解決方案。我將很快用實際的工作代碼和命令更新這個問題。用AES 128加密openssl和解密,ecb模式
客戶端正在用C++加密文件服務器端,我需要在iPhone應用程序中解密它。
我的客戶可以在他身上進行加密和解密,我也可以在iPhone上進行解密,但是我們無法解密彼此加密的文件。 我看到很多關於SO的相關問題,但沒有人能幫助我找到一個在兩邊都以相同方式工作的實現。
我想輸出一些我們將接受的樣本值作爲通用實現。
我試圖用openssl加密文件並用可可解密,但是不能。
以下是我使用的加密:
echo "123456789ABCDEFG" | openssl enc -aes-128-ecb -nosalt -K "41414141414141414141414141414141" -iv 0 > hello.txt.bin
添加選項-p OpenSSL的來電顯示和IV使用的關鍵預期:
key=41414141414141414141414141414141
iv =00000000000000000000000000000000
而對於可可解密(在NSData類別中):
- (NSData *)AESDecryptWithKey:(NSString *)key {
char keyPtr[kCCKeySizeAES128+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 = [self 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;
char iv[32];
for (int i = 0; i < 32; i++) {
iv[i] = 0;
}
CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, kCCOptionECBMode + kCCOptionPKCS7Padding,
keyPtr, kCCKeySizeAES128,
iv, //"00000000000000000000000000000000" /* initialization vector (optional) */,
[self 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;
}
called th是這樣:
- (void)testBinaryFileDecryption {
NSString *databasePath = [[NSBundle mainBundle] pathForResource:@"hello" ofType:@"txt.bin"];
NSData *data = [NSData dataWithContentsOfFile:databasePath];
NSAssert(nil != data, @"Encrypted data, freshly loaded from file should not be nil");
NSData *plain = [data AESDecryptWithKey:@"AAAAAAAAAAAAAAAA"];
NSAssert(nil != plain, @"Decrypted plain data should not be nil");
NSLog(@"Result: '%@'", [[NSString alloc] initWithData:plain encoding:NSASCIIStringEncoding]);
}
結果日誌: Result: '4¨µ¢Ä½Pk£N
我忘記了什麼選擇嗎? NSData的編碼是否返回了NSASCIIStringEncoding以外的內容?
您發現的解決方案發生了什麼?有沒有可能發佈它? – OlivaresF 2011-03-14 01:54:22