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

时间:2017-02-08 14:45:35

标签: java encryption aes

Iam尝试在我的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)

代码:

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);
}

这里出了什么问题?

1 个答案:

答案 0 :(得分:3)

"错误的IV长度:必须长16个字节"你提供的IV字节[]不是16字节长。

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

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

Random rand = new SecureRandom();
byte[] bytes = new byte[16];
rand.nextBytes(bytes);
IvParameterSpec ivSpec = new IvParameterSpec(bytes);