Bhavik Patel
Bhavik Patel

Reputation: 789

Wrong With Encrypt/Decrypt

I have copied source from the answer of this question

and have created this two functions

function my_encrypt($string) {
    $key="1234";
    return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), 
        $string, MCRYPT_MODE_CBC, md5(md5($key))));
}

function my_decrypt($string) {
    $key="1234";
    return rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), 
         base64_decode($string), MCRYPT_MODE_CBC, md5(md5($key))), "\0");
}

And when I tried to encrypt and decrypt using the code shown below

 $string="445676467";
    echo $ecr=my_encrypt($string)."<br/>";
    echo my_decrypt($ecr);

The following output is produced

01pEoOCsp7oloZTDMAKF/cxgB0YQFScje6Z8GBXu8Tw=

445676467›HŽÇeVJMç>ÑÑBHc.–ãyeÇN–=“VSã

Wrong with this is that decrypt is not giving correct ouput which is 445676467

but when I tried directly this

$key="1234";
    $string="2011";
    $encrypted= base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, 
        md5($key), $string, MCRYPT_MODE_CBC, md5(md5($key))));

    $decypted= rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), 
        base64_decode($encrypted), MCRYPT_MODE_CBC, md5(md5($key))), "\0");
    echo $encrypted."<br/>";
    echo $decypted;

this gives the correct answer

Upvotes: 1

Views: 625

Answers (1)

Ofir Baruch
Ofir Baruch

Reputation: 10346

It's funny but the reason is your syntex.

I used your code:

     $string="445676467";
//You echo & put value in the var at the same time?? smells like troubles.
        echo $ecr=my_encrypt($string)."<br/>"; 
        echo my_decrypt($ecr);

Result:

01pEoOCsp7oloZTDMAKF/cxgB0YQFScje6Z8GBXu8Tw=
445676467�H���eVJM�>��BHc.��ye�N�=�VS�

And tried:

 $string="445676467";
    $ecr=my_encrypt($string);
    echo $ecr;
    echo my_decrypt($ecr);

Result:

01pEoOCsp7oloZTDMAKF/cxgB0YQFScje6Z8GBXu8Tw=
445676467

Therefore , nothing wrong with your functions , just the usage. First put the value in the variable and only then print it.

Upvotes: 2

Related Questions