Search code examples
phpaesdestripledes

Triple DES initialization vector


I have a working code to generate encrypt data using PHP:

$cipher_alg = MCRYPT_TRIPLEDES;
$iv = mcrypt_create_iv(mcrypt_get_iv_size($cipher_alg,MCRYPT_MODE_ECB), MCRYPT_RAND); 
$encrypted_string = mcrypt_encrypt($cipher_alg, $pKey, $string, MCRYPT_MODE_ECB, $iv); 

Question is, I run this code multiple time, if the same inputs and always give me the same output for $encrypted_string and a different output for $iv. So why my encrypt data is always the same if the IV changes?


Solution

  • ECB mode does not use an IV, so it doesn't matter what you pass in or that it's different every time. The documentation for mcrypt_encrypt itself indirectly says so:

    iv

    Used for the initialization in CBC, CFB, OFB modes, and in some algorithms in STREAM mode. If you do not supply an IV, while it is needed for an algorithm, the function issues a warning and uses an IV with all its bytes set to "\0".

    You would need to use a chainable mode (CBC etc) to see different results on each iteration -- and in general, ECB mode is a very bad choice. Don't use it.