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

Answers


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.


Need Your Help

Java and sql loop optimization

java sql postgresql loops query-optimization

I'm grabbing a ResultSet from a database of people and ordering them by last names. I also have a table of other people that relate to that other table but since I can't figure out a way to order the

Custom serialization for fields in Rails

ruby-on-rails ruby serialization

Is there a way to have a custom serialization for fields in rails, a method that runs when a field is saved and loaded to convert from/to a string which is what ultimately is saved on the database.