Different results in AES256 encryption in Swift (iOS) and PHP

独自空忆成欢 提交于 2019-11-30 09:09:55

This is due to padding mode differences.

PHP uses "zero padding" if the plain text is not N-times the block size. So PHP pads 0..15 bytes with value 00 for 128 bit block ciphers such as AES. For plaintext that ends on a block boundary it will not add any padding bytes.

Most other languages use PKCS#7 padding, which pads up to the next block boundary, where the padding byte reflects the number of bytes added. So that would be 1..16 bytes with a value of 1..16 (or 01 to 10 in hexadecimals). For plaintext that ends on a block boundary it will add 16 bytes of padding.

PKCS#7 padding is deterministic and does not depend on the plaintext value (which could consist of bytes with any value, not just text); in other words, it can always be applied and removed independent of the content.

Zero padding has the issue that plain text ending with 00 bytes may have those 00 bytes removed during unpadding. This is usually not an issue for ASCII compatible strings as 00 is a control character, usually meaning End Of File (EOF).

Please check the comments on mcrypt_encrypt to see how you can apply PKCS#7 padding to PHP.

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