Dhamu
Dhamu

Reputation: 1752

encrypt and decrypt in php not working

Original URL

/category.php?id=28

After encryptiong

/category.php?id=DyAtftpy3cg4RNtJWT51vFlU5fMVuN+bvaTC365XYkU=

function encryptIt( $q ) {
    $cryptKey  = 'qJB0rGtIn5UB1xG03efyCp';
    $qEncoded      = base64_encode( mcrypt_encrypt( MCRYPT_RIJNDAEL_256, md5( $cryptKey ), $q, MCRYPT_MODE_CBC, md5( md5( $cryptKey ) ) ) );
    return $qEncoded;
}

decrypt

decryptIt($_REQUEST['id']);

used function

function decryptIt( $q ) {
    $cryptKey  = 'qJB0rGtIn5UB1xG03efyCp';
    $qDecoded      = rtrim( mcrypt_decrypt( MCRYPT_RIJNDAEL_256, md5( $cryptKey ), base64_decode( $q ), MCRYPT_MODE_CBC, md5( md5( $cryptKey ) ) ), "\0");
    return $qDecoded;
}

But it returns ���.�_��JC �\Y|{�[=4�V!�o$��

Upvotes: 2

Views: 2306

Answers (2)

PeacefulWarri0r
PeacefulWarri0r

Reputation: 11

Okay, my last post is deleted...

I saw it was working on cli but not through apache.

This was the solution for me:

decryptit(htmlentities($_GET['i'],ENT_QUOTES | ENT_IGNORE, "UTF-8"));

By the way, I use the code from php manual now.

Regards

Upvotes: 1

CodeAngry
CodeAngry

Reputation: 12995

base64_encode( mcrypt_encrypt( MCRYPT_RIJNDAEL_256, md5( $cryptKey ),
    $q, MCRYPT_MODE_CBC, md5( md5( $cryptKey ) ) ) );

should be

base64_encode( mcrypt_encrypt( MCRYPT_RIJNDAEL_256, md5( $cryptKey ),
    $var, MCRYPT_MODE_CBC, md5( md5( $cryptKey ) ) ) );

What's $q? Should it not be $var? (in encryptIt)

WORKS FOR ME:

function decryptIt($data, $key) {
    $key = md5($key);
    $data = base64_decode($data);
    $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_256,
        $key, $data, MCRYPT_MODE_CBC, md5($key));
    $decrypted = rtrim($decrypted, "\0");
    return $decrypted;
}
function encryptIt($data, $key) {
    $key = md5($key);
    $encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_256,
        $key, $data, MCRYPT_MODE_CBC, md5($key));
    $encrypted = base64_encode($encrypted);
    return $encrypted;
}
// Testing
header('Content-Type: text/plain');
$data = 'testing';
$key = 'qJB0rGtIn5UB1xG03efyCp';
$encrypted = encryptIt($data, $key);
// Added your own data here (IT WORKS)
$encrypted = 'DyAtftpy3cg4RNtJWT51vFlU5fMVuN+bvaTC365XYkU=';
echo 'Encrypted: ', $encrypted, '<br>', PHP_EOL;
$decrypted = decryptIt($encrypted, $key);
echo 'Decrypted: ', $decrypted, '<br>', PHP_EOL;

^ Don't know what you're doing wrong but I did something: I stopped the imbricated instruction madness. Assigned variables to each and made the code clear, easy to follow and... functional... I think :)

PS: It's nice to have one-liners but it will torment you if you have bugs in the 1-liners.

Upvotes: 3

Related Questions