AES 256 bit encryption - java.security.InvalidAlgorithmParameterException: Wrong IV length: must be 16 bytes long

喜欢而已 提交于 2019-12-03 04:03:35

You encoded your IV as Base64 before returning it from generateRandomIV. You have to decode it before using it for encryption and decryption.

cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(java.util.Base64.Decoder.decode(IV.getBytes("UTF-8"))));

Java 8 provides the java.util.Base64 class for getting different Base 64 encoders and decoders.

Following the Rob's comment,

System.out.println("number of IV bytes is "+IV.length()+" "+IV);

Here you get the length of the IV in terms of String. However

cipher.init(Cipher.ENCRYPT_MODE, key,new IvParameterSpec(IV.getBytes(Charset.forName("UTF-8"))));    

here you are providing the IV as byte array and making the length of the IV as 16 in therms of String does not guarantee that its byte representation is also 16 bytes. So as Rob suggested it would be better for you to keep the IV in the byte array and use it as the byte array.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!