Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(java.security.InvalidKeyException) No IV set when one expected error at cipher.init(Cipher.DECRYPT_MODE, key)

SecretKey key = keyFactory.generateSecret(keySpec);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] ciphertext = cipher.doFinal(cleartext);

return bytes2String(ciphertext);

I am getting java.security.InvalidKeyException i.e. no IV set when one expected error at cipher.init(Cipher.DECRYPT_MODE, key).cleartext is a byte array resultant of base64 decoding of a string.What am i missing here ?

like image 370
Sourav Bebarta Avatar asked Dec 22 '25 01:12

Sourav Bebarta


1 Answers

I'm no expert at this but, you are specifying CBC mode which requires an initialization vector (IV), which for AES is a 16-byte parameter.

private final static byte[] iv = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
private static final IvParameterSpec ivspec = new IvParameterSpec(iv);

Then when calling init() method provide the IV when encrypting and decrypting.

cipher.init(Cipher.ENCRYPT_MODE, key, ivspec);
cipher.init(Cipher.DECRYPT_MODE, secretKey, ivspec);

You should never use the above approach and let Java generate the random IV for you or provide a SecureRandom implementation.

The point in using a random, IV is to make sure that the same plain text doesn't encrypt to generate the same cipher text twice. That is the sole purpose of the IV.

Store the IV at the beginning of the encrypted text and while decrypting you know that the starting n digits are the IV.

When not providing IV it will by default generate a random IV. Source

If this cipher (including its underlying feedback or padding scheme) requires any random bytes (e.g., for parameter generation), it will get them using the SecureRandom implementation of the highest-priority installed provider as the source of randomness. (If none of the installed providers supply an implementation of SecureRandom, a system-provided source of randomness will be used.)

like image 123
GreyGoose Avatar answered Dec 23 '25 13:12

GreyGoose



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!