2013-05-12 96 views
0

我有與OBJ-C代碼加密的文件:解密用java和AES文件中的OBJ-C加密

NSMutableData *fileData = [NSMutableData new]; 
// Get file data. 
[[self encrypt::fileData WithKey:@"SOME_KEY"]] 

- (NSMutableData*) encrypt:(NSMutableData*)data WithKey: (NSString *) key 
{ 
    // 'key' should be 32 bytes for AES256, will be null-padded otherwise 
    char keyBuffer[kCCKeySizeAES128+1]; // room for terminator (unused) 
    bzero(keyBuffer, sizeof(keyBuffer)); // fill with zeroes (for padding) 

    [key getCString: keyBuffer maxLength: sizeof(keyBuffer) encoding: NSUTF8StringEncoding]; 

    // encrypts in-place, since this is a mutable data object 
    size_t numBytesEncrypted = 0; 

    size_t returnLength = ([data length] + kCCKeySizeAES256) & ~(kCCKeySizeAES256 - 1); 

    char* returnBuffer = malloc(returnLength * sizeof(uint8_t)); 

    CCCryptorStatus result = CCCrypt(kCCEncrypt, kCCAlgorithmAES128 , kCCOptionPKCS7Padding | kCCOptionECBMode, 
           keyBuffer, kCCKeySizeAES128, nil, 
           [data bytes], [data length], 
           returnBuffer, returnLength, 
           &numBytesEncrypted); 

    if(result == kCCSuccess) 
     return [NSMutableData dataWithBytes:returnBuffer length:numBytesEncrypted]; 
    else 
     return nil; 
} 

我想讀用java此文件。我正在嘗試

SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); 
// What is salt ?? 
KeySpec spec = new PBEKeySpec("SOME_KEY", salt, 65536, 256); 
SecretKey tmp = factory.generateSecret(spec); 
SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES"); 
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); 
cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv)); 
String plaintext = new String(cipher.doFinal(ciphertext), "UTF-8"); 
System.out.println(plaintext); 

我對obj-c一無所知。你認爲我能完成這件事嗎?謝謝。

+0

是整體的Objective-C加密代碼嗎?如果沒有,請發佈其餘的。 – 2013-05-13 01:47:24

+0

我使用加密的代碼進行編輯。 – 2013-05-13 08:33:21

回答

0

使用Cipher.getInstance("AES/ECB/PKCS5Padding");因爲Objective-C的代碼是使用ECB而不是CBC(你應該使用CBC或點擊率,而不是歐洲央行,但在這種情況下,它看起來並不像你有一個選擇)

而且,使用SecretKey secret = new SecretKeySpec("SOME_KEY".getBytes("UTF-8"), "AES");,因爲Objective-C代碼只是使用密碼中的原始字節來生成密鑰(而不是像使用加密密鑰生成器那樣)。 「SOME_KEY」需要與Objective-C代碼使用的密碼相同。另外,「SOME_KEY」.getBytes(「UTF-8」)需要恰好爲16個字節,所以如果需要的話,您需要將其截斷爲16個字節,否則將其填充爲0到16個字節。

+0

我做了你的建議,但我有:線程「主」異常javax.crypto.BadPaddingException:給定最後的塊沒有正確填充 – 2013-05-13 20:30:54

+0

@Baptiste Pernet張貼Objective-C輸出/ Java輸入的最後16個字節,所以我可以看看它是如何填充的 – 2013-05-13 20:36:34

+0

,-19,87,-27,-113,98,80,-77,57,-60,31,-68,73,103,51,-36,50] – 2013-05-13 20:41:45