如何在Java中生成一次密钥并在2个不同的程序中使用该密钥

我的目标是编写一个Java程序来使用AES algorithm加密文本文件( cipher text )。 然后,编写另一个程序来解密该加密文件( cipher text )以获取纯文本。 我想使用相同的密钥(相同的密钥,生成一次,保存在某处,并在加密和解密程序中使用它)进行加密和解密过程。 如果我生成密钥并在同一程序中逐行进行加密和解密,那么它可以完美地工作。 以下是该工作代码段:

  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: [B@52b2a2d8 

我可以使用上面的程序获得编码的键值。 但我的问题是如何在我的解密程序中使用此值生成SecretKey?

如果我误解了你的问题,请原谅我,但我相信你希望从字节数组中编码的现有密钥重建一个SecretKey对象。

这可以通过使用javax.crypto.spec.SecretKeySpec的构造函数来执行:

 byte[] encoded = //Key data SecretKey secretKey = new SecretKeySpec(encoded, "AES"); 

由于SecretKeySpecSecretKeySpec的子类,因此不需要强制转换。 如果您的加密/解密算法发生变化,请确保将构造函数AES使用的字符串文字更改为您决定将来使用的算法。

这是以hex打印byte[]数组中的值的一种方法:

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