如何使用Java将secretKey和IV存储在单个文件中以进行AES加密和解密?

use*_*601 2 java encryption aes initialization-vector

我必须使用 AES -256 密码以及 AES 256 密钥和 16 字节 IV 来加密我的文件,我想将密钥和 IV 保存在一个文件中并重新使用它进行解密。但目前我可以单独保存它。任何人都可以帮助我们如何将密钥和 IV 存储在单个文件中。

这是我的代码

SecureRandom srandom = new SecureRandom();
      byte[] iv = new byte[16];
      srandom.nextBytes(iv);
      IvParameterSpec ivspec = new IvParameterSpec(iv);   
      FileOutputStream ivOutFile = new FileOutputStream("C:\\iv.key");
      ivOutFile.write(iv);
      ivOutFile.close();     
      KeyGenerator kgen = KeyGenerator.getInstance("AES");
      kgen.init(256);
      SecretKey skey = kgen.generateKey();
      FileOutputStream out = new FileOutputStream("C:\\AES.key");
      byte[] keyb = skey.getEncoded();
      out.write(keyb);
      out.close(); 
 Cipher ci = Cipher.getInstance("AES/CBC/PKCS5Padding");
          ci.init(Cipher.ENCRYPT_MODE, skey, ivspec);
          FileEncryptionUtils fileEncryptionUtils =new FileEncryptionUtils();
          fileEncryptionUtils.processFile(ci, inFile, outFile);
Run Code Online (Sandbox Code Playgroud)

Luk*_*ark 7

您使用 IV 的方法不正确。静脉注射不是秘密,不应该重复使用。每次加密时都会生成一个新的,并将其与密文一起存储,而不是与密钥一起存储!

有关对称加密的最佳实践,请参阅此存储库中的示例。

  • @user207421 不,它们不是秘密。任何人知道特定密文对应的 IV 都是安全的。对他们来说,预测下一场会发生什么是不安全的。这就是为什么固定 IV 不安全但每次随机生成它们*是*安全的。我再次鼓励您自己研究这个话题,而不是与我争论您不理解的事情。 (2认同)