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

后端 未结 1 517
执念已碎
执念已碎 2020-12-31 09:27

I am working in AES256 to be able to encrypt/decrypt between iOS and PHP using insecure channels.

I have seen many similar questions that move around the key size, t

1条回答
  •  春和景丽
    2020-12-31 10:14

    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.

    0 讨论(0)
提交回复
热议问题