Page 1 of 1

mcrypt decryption problem

Posted: Thu Nov 25, 2004 1:08 am
by voltrader
Hi all...

I'm encrypting/decrypting URL variables but have run into a rare problem. Occasionally, I'll be unable to successfully decrypt a variable. In other words, I encrypt "AAA" and it's decrypted as gibberish. I haven't found anything unusual about the problem variables... they seem to crop up <5% of the time. The code I'm using to encrypt/decrypt variables is:


Code: Select all

<?<?
//$input - stuff to encrypt
//$key - the secret key to use

function _mencrypt($input,$key){
    $input = str_replace("\n","",$input);
    $input = str_replace("\t","",$input);
    $input = str_replace("\r","",$input);
    $key = substr(md5($key),0,24);
    $td = mcrypt_module_open ('tripledes', '', 'ecb', '');
    $iv = mcrypt_create_iv (mcrypt_enc_get_iv_size ($td), MCRYPT_RAND);
    mcrypt_generic_init ($td, $key, $iv);
    $encrypted_data = mcrypt_generic ($td, $input);
    mcrypt_generic_deinit ($td);
    mcrypt_module_close ($td);
    return trim(chop(base64_encode($encrypted_data)));
}


//$input - stuff to decrypt
//$key - the secret key to use

function _mdecrypt($input,$key){
    $input = str_replace("\n","",$input);
    $input = str_replace("\t","",$input);
    $input = str_replace("\r","",$input);
    $input = trim(chop(base64_decode($input)));
    $td = mcrypt_module_open ('tripledes', '', 'ecb', '');
    $key = substr(md5($key),0,24);
    $iv = mcrypt_create_iv (mcrypt_enc_get_iv_size ($td), MCRYPT_RAND);
    mcrypt_generic_init ($td, $key, $iv);
    $decrypted_data = mdecrypt_generic ($td, $input);
    mcrypt_generic_deinit ($td);
    mcrypt_module_close ($td);
    return trim(chop($decrypted_data));
    }
?>
php

?>