Where to put information about padding length?

自作多情 提交于 2019-12-11 13:17:28

问题


I'm working on AES encryptor and decryptor. I've decided to use PKCS#7. And now, I've no idea where to put information about padding length. I've read that I can read last byte (==n) and check if it's lower than 16. If it's true i can check n bytes if they are equal n. But here is a thing. What if the last block to encrypt has 16 bytes and looks like this for exmaple:

{0x01, 0xfa,..., 0xf1, 0x02, 0x02}

After decryption, decryptor will read it and decide that two last bytes are padded (in fact they are not).

Should I add byte at the begining of a file with length, and decryptor will read it and start decrypting from second byte?


回答1:


PKCS#7 padding is deterministic. That means that unpadding should always be able to find out the padding length itself. So you first decrypt, then take the last byte (as number) and that is the padding length. For this to work, PKCS#7 padding is always applied. So the amount of padding, and thus the value of the bytes, is 1 to the blocksize, which is 16 bytes for AES. . If the plaintext is already dividable by 16, a full block of padding - with bytes valued 16 / 0x10 is applied.

In short, the calculation is:

p = n - l % n

where p is the pad size & value, n is the block size and l is the size of the plaintext.




回答2:


The best practice is to add 32bit prefix with the actual length before encrypted data.



来源:https://stackoverflow.com/questions/26930911/where-to-put-information-about-padding-length

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