2013-11-27 41 views
4

我的目標是使用AES algorithm編寫一個Java程序來加密文本文件(cipher text)。然後,編寫另一個程序來解密該加密文件(cipher text)以獲取純文本。我想使用相同的密鑰(相同的密鑰,生成一次,保存在某個地方,並將其用於加密和解密程序)進行加密和解密過程。如果我生成密鑰並在同一個程序中逐行執行加密和解密,那麼它可以很好地工作。這裏是該工作代碼片段:如何在Java中生成一次密鑰並在兩個不同的程序中使用該密鑰

 String strDataToEncrypt = new String(); 
     String strCipherText = new String(); 
     String strDecryptedText = new String(); 

     KeyGenerator keyGen = KeyGenerator.getInstance("AES"); 
     keyGen.init(128); 
     SecretKey secretKey = keyGen.generateKey(); 

     Cipher aesCipher = Cipher.getInstance("AES"); 
     aesCipher.init(Cipher.ENCRYPT_MODE,secretKey); 

     strDataToEncrypt = "any text input"; 
     byte[] byteDataToEncrypt = strDataToEncrypt.getBytes(); 
     byte[] byteCipherText = aesCipher.doFinal(byteDataToEncrypt); 
     strCipherText = new BASE64Encoder().encode(byteCipherText); 
     System.out.println("cipher text: " +strCipherText); 
     aesCipher.init(Cipher.DECRYPT_MODE,secretKey,aesCipher.getParameters()); 
     byte[] byteDecryptedText = aesCipher.doFinal(new BASE64Decoder().decodeBuffer(strCipherText)); 
     strDecryptedText = new String(byteDecryptedText); 
     System.out.println("plain text again: " +strDecryptedText); 

但是,我需要有兩個不同的程序(java文件)進行加密和解密。所以,我必須以某種方式生成一個密鑰並保存在某個地方。然後對加密和解密程序使用相同的密鑰。我怎樣才能做到這一點?

EDIT_1

KeyGenerator keyGen = KeyGenerator.getInstance("AES"); 
keyGen.init(128); 
SecretKey secretKey = keyGen.generateKey(); 
byte[] encoded = secretKey.getEncoded(); 
System.out.println("key: "+encoded);// key: [[email protected] 

我可以使用上述程序編碼的鍵值。但我的問題是如何在解密程序中使用此值生成SecretKey?

+0

您生成了一個密鑰,什麼阻止您將其寫入文件,然後在第二個程序中讀取它? –

+0

@JimGarrison請看看我的編輯。 –

+0

關鍵是系統使用'Object#toString()'的'byte []',它只是寫出內部身份。您需要將單個字節_values_寫入文件,也許先將它們轉換爲十六進制。 –

回答

11

原諒我,如果我誤解了你的問題,但我相信你希望從現有的密鑰編碼重建SecretKey對象在一個字節數組中。

這可以簡單地通過使用javax.crypto.spec.SecretKeySpec的構造這樣進行:

byte[] encoded = //Key data 

SecretKey secretKey = new SecretKeySpec(encoded, "AES"); 

SecretKeySpec由於是SecretKey一個子類不需要鑄造。如果您的加密/解密算法改變,請確保將構造函數AES中使用的字符串文字更改爲您將來決定使用的任何算法。

+1

謝謝,我使用Base64Coder將密鑰轉換爲十六進制字符串並保存到首選項,然後檢索密鑰並使用Base64Coder對其進行解碼,並完美運行。 – Diljeet

1

這裏的一個的方式打印出來的值在byte[]陣列中的十六進制:

byte[] a = {-120, 17, 42,121}; 
for (byte b : a) 
{ 
    System.out.printf("%2X",b); 
} 
System.out.println(); 
+0

我也可以使用:Arrays.toString(byte []) 來獲取字節數組的內容。但是,我不確定如何使用此值初始化SecretKey。仍然在挖掘它。 –

+0

如果使用'Arrays.toString(byte [])',你將經歷一個字節到字符的編碼轉換,這個轉換可能是不可逆的。 –

+0

['Arrays.toString(byte [])'](http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#toString(byte []))被定義爲產生非常不可能改變的陣列的標準表示。但是我同意這絕對不適合這個目的。 @KeenLearner考慮十六進制或Base64編碼,如果你需要用ASCII碼錶示密鑰,並且記住文件可以包含二進制數據。 – ntoskrnl

相關問題