我的目标是使用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_写入文件,也许先将它们转换为十六进制。 –