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

标签 java cryptography aes secret-key

我的目标是编写一个 Java 程序来使用 AES 算法 加密文本文件(密文)。然后,编写另一个程序来解密该加密文件(密文)以取回明文。我想使用相同的 key (相同的 key ,生成一次,将其保存在某个地方,并在加密和解密程序中使用它)进行加密和解密过程。如果我生成 key 并在同一个程序中逐行进行加密和解密,那么它就可以完美运行。这是它的工作代码片段:

        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 文件)来进行加密和解密。所以,我必须以某种方式生成一个 key 并将其保存在某个地方。然后对加密和解密程序使用相同的 key 。我该怎么做?

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?

最佳答案

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

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

byte[] encoded = //Key data

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

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

关于java - 如何在 Java 中生成一次 key 并在 2 个不同的程序中使用该 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20233775/

相关文章:

java - 通过 JDBC 连接的 SQL 查询速度较慢,具体取决于访问数据源对象的位置

java - 如何制作消息布局

python - 在 Python 中使用 RSA 公钥进行签名许可证 key 验证

javascript - 验证解密的字符串

Node.js Crypto,AES 的默认填充是什么?

Android/Java 使用 cipher.getOutputSize() 分配字节时内存不足 "OutOfMemoryError"

java - 使用本地库覆盖 Maven 依赖项

java - 使用 ANT 和 Eclipse 自动创建 JAR

cryptography - 具有随机移位加密的二进制字符串

c++ - 错误 : AES Encryption key: invalid conversion from ‘char*’ to ‘unsigned char’