Why is mcrypt_encrypt() putting binary characters at the end of my string?

主宰稳场 提交于 2019-11-28 01:07:25

The returned string is padded out to fill n * blocksize bytes using the null character \0 so that is why you are seeing the extra data.

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

It seems to be a known problem. Use rtrim() after decoding to remove the excess NULs.

You're receiving null bytes because you're using Electronic Code Block (ECB) for your block cipher mode of operation, which pads the end of your plaintext to fit into the block size. In your case the block size is 256 bits because you're using MCRYPT_RIJNDAEL_256.

You can avoid this padding problem all together if you use Cipher Feedback (CFB) mode — MCRYPT_MODE_CFB — no null bytes, no need to trim. But, with CFB you should HMAC your encrypted data, to verify it hasn't been tampered with (see "Mallet"). You can find an example of a working implementation at: Cryptography For The Average Developer.

Also of note, ECB mode is considered less secure because it can reveal data patterns. Plus, ECB (and CBC since it also pads) can be vulnerable to padding oracle attack.

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

mcrypt_encrypt — Encrypts plaintext with given parameters

You can use base64_encode($text) for use plaintext.

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