AES java.security.InvalidAlgorithmParameterException: 错误的 IV 长度:必须是 16 字节长

Abh*_*988 0 java encryption aes

我试图在我的 Java 应用程序中使用 AES 加密来加密数据。当我运行代码(如下所示)时,我得到:

java.security.InvalidAlgorithmParameterException: Wrong IV length: must be 16 bytes long
    at com.sun.crypto.provider.CipherCore.init(CipherCore.java:525)
    at com.sun.crypto.provider.AESCipher.engineInit(AESCipher.java:346)
    at javax.crypto.Cipher.implInit(Cipher.java:806)
    at javax.crypto.Cipher.chooseProvider(Cipher.java:864)
    at javax.crypto.Cipher.init(Cipher.java:1396)
    at javax.crypto.Cipher.init(Cipher.java:1327)
    at TestEncription.encryptData(TestEncription.java:164)
    at TestEncription.encodeRequest(TestEncription.java:109)
    at TestEncription.main(TestEncription.java:65)
Run Code Online (Sandbox Code Playgroud)

代码:

public String encryptData(String requestData, byte[] sessionKey,
        String messageRefNo) throws Exception {

    SecretKey secKey = new SecretKeySpec(sessionKey, "AES");
    Cipher cipher = Cipher.getInstance(symmetricKeyAlgorithm);
    IvParameterSpec ivSpec = new IvParameterSpec(messageRefNo.getBytes("UTF-8"));
    System.out.println("Seckey: "+secKey);
    cipher.init(Cipher.ENCRYPT_MODE, secKey, ivSpec);
    byte[] newData = cipher.doFinal(requestData.getBytes());

    return Base64.encodeBase64String(newData);
}
Run Code Online (Sandbox Code Playgroud)

这里出了什么问题?

Pet*_*rey 5

“错误的 IV 长度:必须是 16 字节长”您提供的 IV 字节 [] 不完全是 16 字节长。

正如@zaph 指出的那样,不使用随机序列会破坏拥有 IV 的目的。

您应该做的是提供一个随机序列,例如

Random rand = new SecureRandom();
byte[] bytes = new byte[16];
rand.nextBytes(bytes);
IvParameterSpec ivSpec = new IvParameterSpec(bytes);
Run Code Online (Sandbox Code Playgroud)