Search code examples
opensslphp-openssl

How to properly generate an IV


I'd like to encrypt some data, with symmetric-key encoding, using AES-256 in CBC mode. I saw different implementations on the web, which way is the best (if is there any) to generate a proper IV?

Method 1:

$secret_iv = 'This is my secret iv';
$iv = substr(hash('sha256', $secret_iv), 0, 16);

IV is simply generated with sha256 by some input (As I know it is better to use different IV for each encrypted data, so I'd generate some random stuff as the seed of the sha265 hash). The IV then truncated to length of 16 because that's what AES-256-CBC is expecting.

Method 2:

$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));

openssl_random_pseudo_bytes generates some binary output with a length of 16.

Is there any significant difference in using classic string or binary string as the IV?


Solution

  • The IV is composed of bytes.

    Whether these bytes can be represented as a string or not, does not matter.

    In order to increase the security, you should generate a random IV.

    Indeed, given an encryption key, if the IV is chosen at random, and if you encrypt the same plain text twice, this won't result in the same cipher text.

    So you should prefer Method 2 in your example.