Why does mcrypt_encrypt () put binary characters at the end of my line?

Here is a demo version of a PHP script that encrypts and decrypts data:

<? $encryptionkey = 'h8y2p9d1'; $card_nbr = "1234"; echo "original card_nbr: $card_nbr <br>\n"; $card_nbr_encrypted=encrypt_data($card_nbr); echo "card_nbr_encrypted: $card_nbr_encrypted <br>\n"; $card_nbr_decrypted=decrypt_data($card_nbr_encrypted); echo "card_nbr_decrypted: $card_nbr_decrypted <br>\n"; $len=strlen($card_nbr_decrypted); echo "length: $len <br>\n"; function encrypt_data($text){ global $encryptionkey; $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB); $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND); $encrypted_text = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $encryptionkey, $text, MCRYPT_MODE_ECB, $iv); return $encrypted_text; } function decrypt_data($text){ global $encryptionkey; $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB); $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND); $decrypted_text = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $encryptionkey, $text, MCRYPT_MODE_ECB, $iv); return $decrypted_text; } ?> 


Exit:

 original card_nbr: 1234 card_nbr_encrypted: vY¨(Z$<§G3-žÃ-Éù3Ý2Ê×rz¨VÛ card_nbr_decrypted: 1234 (and 28 binary characters) length: 32 


The output is successfully decrypted, but 28 binary characters are added to the end. This can be most easily seen in Firefox when viewing an HTML source. A line of length 32 also demonstrates this. Any ideas?

enter image description here

+8
php encryption mcrypt
source share
4 answers

The returned string is filled to fill n * blocksize bytes using the null character \0 , so you see additional data.

If you run $card_nbr_decrypted= rtrim($card_nbr_decrypted, "\0"); , he must return the actual data.

+8
source share
+3
source share

You get zero bytes because you use the Electronic Code Block (ECB) for block cipher mode , which puts the end of your plaintext on the block size. In your case, the block size is 256 bits because you are using MCRYPT_RIJNDAEL_256 .

You can avoid this add-on problem if you use encryption feedback mode (CFB) - MCRYPT_MODE_CFB - there are no null bytes, no need to trim. But with CFB, you must HMAC your encrypted data to make sure that it has not been modified (see "Mallet") . You can find an example of a working implementation at: Cryptography for the average developer .

It should also be noted that ECB mode is considered less secure because it can display data patterns . In addition, the ECB (and the CBC since it also builds) may be vulnerable to complement Oracle attacks .

+2
source share

I think the problem is that you are using binary data when:

mcrypt_encrypt - Encrypts plaintext with the given parameters

You can use base64_encode ($ text) to use plain text.

-one
source share

All Articles