I'm almost new to encryption.
I am trying to decrypt an array of bytes, and when I am providing the IV I am getting an exception : InvalidAlgorithmParameterException (no iv set when one expected).
Here's my code (iv is an array of 16 bytes which is not null and has the values used when encrypting) :
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, encriptionKey,new IvParameterSpec(iv));
If I don't specify the IV the cipher gets initialized ok :
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, encriptionKey);
Trying to find an answer I did find an implementation of JCEStreamCipher (here) which may not correspond to the version I am using but has some code that makes me thing I am not understanding it correctly.
Here's the code :
if ((ivLength != 0) && !(param instanceof ParametersWithIV))
{
SecureRandom ivRandom = random;
if (ivRandom == null)
{
ivRandom = new SecureRandom();
}
if ((opmode == Cipher.ENCRYPT_MODE) || (opmode == Cipher.WRAP_MODE))
{
byte[] iv = new byte[ivLength];
ivRandom.nextBytes(iv);
param = new ParametersWithIV(param, iv);
ivParam = (ParametersWithIV)param;
}
else
{
throw new InvalidAlgorithmParameterException("no IV set when one expected");
}
}
Looks like I cannot provide an IV when decrypting, but it doesn't makes too much sense to me.
any help will be greatly appreciated.
thanks a lot, richard.
Solved.
I was using a wrong SecretKey, not the one you can create for AES.
Previously I had :
KeySpec spec = new PBEKeySpec(password.toCharArray(), encryptionKeySalt, 12345,256);
SecretKey encriptionKey = factory.generateSecret(spec);
which creates a JCEPBEKey.
I was missing :
Key encriptionKey = new SecretKeySpec(encriptionKey.getEncoded(), "AES");
which creates an appropiate key for AES.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With