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

前端 未结 4 1943
有刺的猬
有刺的猬 2020-12-06 18:33

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



        
4条回答
  •  悲&欢浪女
    2020-12-06 18:59

    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.

提交回复
热议问题