我的目标是编写一个Java程序,使用AES算法加密文本文件(密文)。然后,编写另一个程序来解密该加密文件(密文)以获取明文。我想在加密和解密过程中使用相同的密钥(同一密钥,生成一次,保存在某个地方,并在加密和解密程序中使用)。如果我在同一个程序中生成密钥并逐行进行加密和解密,则它可以完美地工作。以下是该功能的代码片段:
我可以使用上述程序获取编码的密钥值。但我的问题是如何在我的解密程序中使用此值生成SecretKey?
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文件)用于加密和解密。因此,我必须以某种方式生成一个密钥并将其保存在某个地方。然后在加密和解密程序中使用相同的密钥。我该怎么做?
编辑_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?
byte[]
,系统使用Object#toString()
,它只写出内部标识。你需要将各个 byte 值写入文件中,也可以先将其转换为十六进制。 - Jim Garrison