Question

I'm having a problem when writing and parsing some DATA out of stored cookies.

Here are my crypt and decrypt functions (which I have found in another topic here).

function decrypt($crypttext){   
        $crypttext = base64_decode($crypttext);
        $plaintext = '';
        $td        = mcrypt_module_open(MCRYPT_RIJNDAEL_256, '', MCRYPT_MODE_CBC, '');
        $ivsize    = mcrypt_enc_get_iv_size($td);
        $iv        = substr($crypttext, 0, $ivsize);
        $crypttext = substr($crypttext, $ivsize);
        if ($iv)
        {
            mcrypt_generic_init($td, CRYPTKEY, $iv);
            $plaintext = mdecrypt_generic($td, $crypttext);
        }
        return trim($plaintext);
}

function encrypt($plaintext){
        $td = mcrypt_module_open(MCRYPT_RIJNDAEL_256, '', MCRYPT_MODE_CBC, '');
        $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
        mcrypt_generic_init($td, CRYPTKEY, $iv);
        $crypttext = mcrypt_generic($td, $plaintext);
        mcrypt_generic_deinit($td);
        return base64_encode($iv.$crypttext);
} 

My usage is fairly simple:

//read, split if neccesarry, check if already in it, if not-> add, crypt, write
if(isset($_COOKIE['DATA'])){

    $data = decrypt($_COOKIE['DATA']);

    $search = explode('#',$data);
    if(!in_array($lnk, $search)){
        $data.= "#".$lnk; // $lnk = additional data
        $err = setrawcookie("DATA", encrypt($data));
    }
    $err = true;
}

In most tries, it doesn't work adding a $lnk. The decryption of the cookie after I've wrote it, is wrong. undefined junk. (so something doesn't work well).

I haven't been able to find any errors in the code at all. My best guess is that the problem is caused by :

  $ivsize    = mcrypt_enc_get_iv_size($td);
  $iv        = substr($crypttext, 0, $ivsize);

Specifically, that $ciphertext is smaller than $ivsize?

Any other ideas?

// to prevent questions about it: the data which i store, are just php uniqueID()'s separeted by '#'. so maybe in future there will be 10 IDs stored (encrypted) in the cookie...i didin't know the max size of a cookie and the factor AES blow this up, but i thought a cookie should get it.

(if there is a easier synchronus way to encrypt (this should not be high security, but mostly safe) please feel free to tell me.

Was it helpful?

Solution

Try using bin2hex instead of base64_encode(). I previously answered a similar question on SO.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top