I'm using javax.crypto to do some cryptographic operations in my application. I use AES for encryption/decryption like this:
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
byte[] cipherText = cipher.doFinal(plaintext);
byte[] iv = cipher.getIV(); //The problematic IV
The generated IV is prepended to the ciphertext after the enncryption.
The Java specification clearly says that the IV must be generated automatically if its is not provided to cipher.init()
:
If this cipher requires any algorithm parameters that cannot be derived from the given key, the underlying cipher implementation is supposed to generate the required parameters itself (using provider-specific default or random values)
But sometimes I end up with ciphertexts that don't seem very random, such as this one (in base64):
AAAAAAAAAAAAAAAAAAAAAOmI9Qh1fMiG6HV3tKZK3q5sCruaPdYqYnoUOM00rs6YZY3EvecYfR6vTHzZqk7ugknR9ZMipedYWJB1YOLmSYg=
The bunch of A
characters at the front is the IV. The IV is actually 16 zero-bytes.
Most of the time, the library generates proper, random IVs, but sometimes, it just pops out zeros. Why is this happening?