2015-05-14 72 views
0

我想解密使用Microsoft CryptoAPI的CryptEncrypt函數加密的Java文件。我已經讀過:「返回的加密塊緩衝區採用小端字節順序(與上面的Java和.NET的big-endian相比)。」java的ByteOrder小endian大endian不工作?

我正在使用Java中的ByteBuffer和ByteOrder類,並且很確定我做錯了,因爲無論我嘗試什麼,我都會得到與System.out.println相同的打印輸出以用於beforebytes和afterbytes。

byte [] beforebytes = null; 

// code to extract bytes from file here 

ByteBuffer bb = ByteBuffer.wrap(beforebytes); 

bb.order(ByteOrder.LITTLE_ENDIAN); // BIG_ENDIAN doesn't work either? 

ByteBuffer slice = bb.slice(); 
// 'slice' now refers to the same data, but is supposed to be BIG ENDIAN 

byte[] afterbytes = new byte[bb.capacity()]; 

// transfer bytes from this buffer into the given destination array 
slice.get(afterbytes, 0, afterbytes.length); 

任何幫助將不勝感激!

謝謝 貝特朗

+0

你可以在你的問題的正文中包括你嘗試過的東西嗎? – Newd

+0

嗨Newd,我試過ByteOrder.BIG_ENDIAN。我嘗試過和沒有切片。我也嘗試了其他明顯錯誤的東西;) –

回答

0

的字節順序,如果你得到單個字節(或字節數組)移出緩衝區無所謂。只有當您從緩衝區中獲得例如16位短值或32位整數值時才重要;在這種情況下,緩衝區中的字節將根據字節順序進行適當的交換。

例如:

ByteBuffer buf1 = ByteBuffer.wrap(new byte[]{0x01, 0x02, 0x03, 0x04}); 
buf1.order(ByteOrder.LITTLE_ENDIAN); 

int n1 = buf1.getInt(); 
System.out.println(n1 == 0x04030201); 

ByteBuffer buf2 = ByteBuffer.wrap(new byte[]{0x01, 0x02, 0x03, 0x04}); 
buf2.order(ByteOrder.BIG_ENDIAN); 

int n2 = buf2.getInt(); 
System.out.println(n2 == 0x01020304); 
+0

謝謝你的迴應。從你的回答中,我瞭解到切片和容量方法是多餘的。但是,將它移到afterbytes字節數組的正確語法是什麼? –

1

我用C解決了這個! Java現在可以正確解密由CryptoAPI加密的內容。

我從在CryptoAPI的示例開始了: http://blogs.msdn.com/b/alejacma/archive/2008/01/28/how-to-generate-key-pairs-encrypt-and-decrypt-data-with-cryptoapi.aspx

然後剛寫入的加密文本到文件之前,我添加的代碼塊從參考 CryptoAPI C++ interop with Java using AES

// reverse bytes of pbData for java 
for (unsigned i = 0; i<dwEncryptedLen/2; i++) 
{ 
BYTE temp = pbData[i]; 
pbData[i] = pbData[dwEncryptedLen - i - 1]; 
pbData[dwEncryptedLen - i - 1] = temp; 
} 

基準是爲AES但我在RSA中加密。對於解密,我使用算法「RSA/NONE/PKCS1Padding」使用了bouncycastle提供程序。要在Windows 7上安裝bouncycastle提供程序,請按照:http://sce.uhcl.edu/yang/teaching/JDK_JCE_environment_Configuration.htm重新啓動

希望這會幫助別人。