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); $key = md5($key); $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);
if (mcrypt_generic_init($td, $key, $iv) != -1) {
$c_t = mcrypt_generic($td, $string);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
$c_t = $iv.$c_t;
return $c_t;
} }
function my_decrypt($string,$key) {
$key = md5($key); $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);
if (mcrypt_generic_init($td, $key, $iv) != -1) {
$c_t = mdecrypt_generic($td, $string);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return $c_t;
} }
?>