note 40434 added to function.mcrypt-create-iv

From: Date: Wed, 03 Mar 2004 17:25:20 +0000
Subject: note 40434 added to function.mcrypt-create-iv
Groups: php.notes 
Request: Send a blank email to php-notes+get-66178@lists.php.net to get a copy of this message
It is important to note that all cipher modes except ecb require the same IV to be used in decryption as was used in encryption. You need to pass the key *and* the IV to your decrypt function. Initializing a new IV in the decrypt routine will not work. Since, "you even can send [the IV] along with your ciphertext without loosing security," a nice way to handle this is to prepend your IV to your ciphertext. Since the IV is fixed-width, you can then easily recover the IV and original ciphertext using mcrypt_get_iv_size() and substr(). Here is an example: <?PHP function my_encrypt($string,$key) { srand((double) microtime() * 1000000); //for sake of MCRYPT_RAND $key = md5($key); //to improve variance /* Open module, and create IV */ $td = mcrypt_module_open('des', '','cfb', ''); $key = substr($key, 0, mcrypt_enc_get_key_size($td)); $iv_size = mcrypt_enc_get_iv_size($td); $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND); /* Initialize encryption handle */ if (mcrypt_generic_init($td, $key, $iv) != -1) { /* Encrypt data */ $c_t = mcrypt_generic($td, $string); mcrypt_generic_deinit($td); mcrypt_module_close($td); $c_t = $iv.$c_t; return $c_t; } //end if } function my_decrypt($string,$key) { $key = md5($key); //to improve variance /* Open module, and create IV */ $td = mcrypt_module_open('des', '','cfb', ''); $key = substr($key, 0, mcrypt_enc_get_key_size($td)); $iv_size = mcrypt_enc_get_iv_size($td); $iv = substr($string,0,$iv_size); $string = substr($string,$iv_size); /* Initialize encryption handle */ if (mcrypt_generic_init($td, $key, $iv) != -1) { /* Encrypt data */ $c_t = mdecrypt_generic($td, $string); mcrypt_generic_deinit($td); mcrypt_module_close($td); return $c_t; } //end if } // to test: //print my_decrypt(my_encrypt("Hello, world.","foo"),"foo"); ?> ---- Manual Page -- http://www.php.net/manual/en/function.mcrypt-create-iv.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+40434 Delete -- http://master.php.net/manage/user-notes.php?action=delete+40434&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+40434&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#66178) next »