当我使用默认的 AES/GCM 算法初始化 Cipher 对象时,它有一个随机的 12 个字节的 IV,但前 4 个字节在调用 doFinal 后不会增加并抛出java.lang.IllegalStateException:无法重新使用相同的密钥和IV 用于多重加密例外。
SecretKey secretKey = ...
final Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] iv1 = encCipher.getIV();
byte[] ctext = encCipher.doFinal("a".getBytes());
cipher.update("b".getBytes());
byte[] iv2 = encCipher.getIV();
ctext = encCipher.doFinal();
Run Code Online (Sandbox Code Playgroud)