我的目标是编写一个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");
由于SecretKeySpec
是SecretKey
的子类,因此不需要强制转换。如果您的加密/解密算法发生更改,请确保将构造函数AES
中使用的字符串文字更改为您决定将来使用的任何算法。
这里有一种以十六进制打印byte[]
数组中的值的方法:
byte[] a = {-120, 17, 42,121};
for (byte b : a)
{
System.out.printf("%2X",b);
}
System.out.println();