Search code examples
javaperlencryptioncryptographyaes

proper formatting of initialization vectors in perl using AES CBC


I am trying to decrypt in perl a string that was encrypted in java using AES/CBC. What I am struggling with is that the encrypted output does not seem to have the initialization vector prepended as the first 16 bytes of the output. For a proof of concept to verify that my decryption algorithm is working as expected, I would like to hardcode the initialization vector in my perl script.

I am using Crypt::CBC, but when passing the initialization vector to this library, I am not sure what kind of format it is expecting. I have tried simply passing in the initialization vector as a string, e.g.

$my iv = "0000000000000000"; 

but it does not seem to work as decrypting with this initialization vector produces no output.

So my question is, if the initialization vector is created as follows in java:

byte[] iv = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6 };
IvParameterSpec ivspec = new IvParameterSpec(iv);

how can I replicate this initialization vector in perl?


Solution

  • The equivalent of the Java IV would be

    my $iv = "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x00\x01\x02\x03\x04\x05\x06";
    

    and

    my $iv = pack("C*", 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6);
    

    Note that you shouldn't use a constant IV. That defies the point, resulting in broken security. You should use completely random bytes, and they should be different for each message/stream you encode. Now, it sounds like you're only doing this for testing, in which case you can forget I said anything :)