Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decrypting error : "no iv set when one expected"

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.

like image 816
richardtz Avatar asked Jul 16 '12 11:07

richardtz


1 Answers

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.

like image 108
richardtz Avatar answered Oct 06 '22 18:10

richardtz