5

我的目标是编写一个 Java 程序来cipher text使用AES algorithm. 然后,编写另一个程序来解密该加密文件 ( 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?

4

2 回答 2

18

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

这可以通过使用javax.crypto.spec.SecretKeySpec的构造函数来简单地执行,如下所示:

byte[] encoded = //Key data

SecretKey secretKey = new SecretKeySpec(encoded, "AES");

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

于 2013-12-15T05:34:23.783 回答
1

这是以十六进制打印出数组中的值的一种方法:byte[]

byte[] a = {-120, 17, 42,121};
for (byte b : a)
{
    System.out.printf("%2X",b);
}
System.out.println();
于 2013-11-27T04:39:53.097 回答