我的目標是使用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?
您生成了一個密鑰,什麼阻止您將其寫入文件,然後在第二個程序中讀取它? –
@JimGarrison請看看我的編輯。 –
關鍵是系統使用'Object#toString()'的'byte []',它只是寫出內部身份。您需要將單個字節_values_寫入文件,也許先將它們轉換爲十六進制。 –