PHP MCRYPT encrypt/decrypt returns invisible strange characters?

老子叫甜甜 提交于 2019-12-20 04:13:57

问题


mcrypt_decrypt is giving me additional invisible characters which are NOT VISIBLE by just echoing out on the page. Can ONLY BE SEEN by writing it to the text file. Means, just displaying on the page is OK and hard to be noticed.

Here is the code sample by Googling. Please guide me what is the correct usage is there's something wrong:

function encrypt ($pure_string, $key) {
    $iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_ECB);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    $encrypted_string = mcrypt_encrypt(MCRYPT_BLOWFISH, $encryption_key, $pure_string, MCRYPT_MODE_ECB, $iv);
    return $encrypted_string;
}

function decrypt ($encrypted_string, $key) {
    $iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_ECB);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    $decrypted_string = mcrypt_decrypt(MCRYPT_BLOWFISH, $encryption_key, $encrypted_string, MCRYPT_MODE_ECB, $iv);
    return $decrypted_string;
}

but when i try it:

$encrypted_string = encrypt("This is the original string.", "ABC123");
echo decrypt($encrypted_string, "ABC123");

.. i am getting something like:

This is the original string.�������

This strange characters ������� are actually not visible when you/ i just echo it. Can only be seen by writing into the text file.

  • So what am i missing please?
  • Is there any perfect way to achieve this encrypt/decrypt?

Thank you.


回答1:


You can use trim($string, "\0\4") to cut out these characters.




回答2:


rtrim() will remove the padding that mcrypt added...




回答3:


This is padding. ECB mode requires input to be multiple of cipher block size, so additional bytes are added (most likely it is PKCS#5 padding).

To remove PKCS#5 padding you can use following code:

$dec_s = strlen($decrypted);
$padding = ord($decrypted[$dec_s-1]);
$decrypted = substr($decrypted, 0, -$padding); 



回答4:


function encrypt ($pure_string, $key) {

=> $key

$encrypted_string = mcrypt_encrypt(MCRYPT_BLOWFISH, $encryption_key, $pure_string, MCRYPT_MODE_ECB, $iv);

=> $encryption_key

not equal



来源:https://stackoverflow.com/questions/16895540/php-mcrypt-encrypt-decrypt-returns-invisible-strange-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!