PHP MCRYPT encrypt / decrypt returns invisible weird characters?

mcrypt_decrypt gives me extra invisible characters that are NOT visible, just an echo on the page. THERE IS ONLY TO SEE, writing it to a text file. So, just displaying on the page is fine and hard to notice.

Here is a sample code on Google. Please tell me what is the right use, something is 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 get something like:

 This is the original string.        

These weird characters not actually visible when you / i are just echo . Can only be displayed in a text file.

  • So what will I miss, please?
  • Is there any perfect way to achieve this encryption / decryption?

Thanks.

0
source share
4 answers

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

+2
source

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

+1
source

This is an addition. ECB mode requires the input to be a multiple of the size of the encryption block, so additional bytes are added (most likely this is PKCS # 5 add-on).

To remove the PKCS # 5 add-on, you can use the following code:

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

encrypt function ($ pure_string, $ key ) {

=> $ key

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

=> $ encryption_key

not equal

-2
source

Source: https://habr.com/ru/post/1242345/


All Articles