views:

463

answers:

5

I Encrypt and Decrypt successfully, but when I decrypt the value, appears strange characters at the final of string "���": The initial $_POST['value'] do not have any blank space or any strange character

Any idea to solve this?

Encrypt with this:

$key='my key';
$td = mcrypt_module_open('tripledes', '', 'ecb', '');
$iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
mcrypt_generic_init($td, $key, $iv);     
$id = mcrypt_generic($td, $_POST['value']);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);

Decrypt with this:

$key='my key';
$td = mcrypt_module_open('tripledes', '', 'ecb', '');
$iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
mcrypt_generic_init($td, $key, $iv);
$id = mdecrypt_generic($td, $_COOKIE['value']);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
+2  A: 

These are unicode entities. Try utf8_decode() on the output.

There is also a related closed PHP Bug

mcrypt produces binary output which is neither iso-8859-1 nor utf-8 therefore you should tell your database that that data is binary stuff, not text data.

I also found this info on the mcrypt example page.

I could En/Decrypt within VB and PHP just fine But when I tried to encrypt one in VB and decrypt in PHP I got the wrong values with the mcrypt function alone

I found that at least with VB9 that the stream encryption uses a UTF char that is the value for how many missing bytes left in the 8 bit stream.

So if you encrypt 1234 it will add chr(4) four times (the amount of missing bytes) In php use chr otherwise most browsers/client cant read it. Im not good at explaining things but the php code I figured out is below.

Ólafur Waage
A: 

Not is from VB is from PHP(encrypt) and PHP(decrypt) and the page is utf-8 and database is utf-8 and the conection i utf-8.

Not is from all, I encrypt 2 passprases, the first have strange characters and the last doesn't have, all values are POST from the same .

A: 

Use following function for decrypted text

function pkcs5_unpad($text)
{
    $pad = ord($text{strlen($text)-1});
    if ($pad > strlen($text)) return false;
    if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) return false;
    return substr($text, 0, -1 * $pad);
}
John
+1  A: 

Try to switch to cfb instead of ecb mode, then rewrite the functions to use the same IV for both encryption and decryption. An easy way to do that is passing IV along with the encrypted data (I assume you've got something like "return $encrypted_data" at the end of your function, you may return $iv.$encrypted_data instead of $encrypted_data itself, and then get the IV back with substr() ). Worked for me.

Marf
A: 

It just padding the result based on the block size used. If you use rtrim(), you will get rid of them.

Ben