somesocks / lua-lockbox

A collection of cryptographic primitives written in pure Lua
MIT License
362 stars 75 forks source link

how to unpadding when i use ZeroPadding in AES128Cipher #19

Closed zk0318 closed 7 years ago

zk0318 commented 7 years ago

it is my eg: local iv = Array.fromHex("545e7a772453377d5e29405941615125"); local key = Array.fromHex(String.lower(res)); local plaintext = Array.fromHex("f69f2445df4f9b17ad2b417be66c3710"); local ciphertext = Base64.toArray("L0zArIO+yh3ILdCIXUm91VgP5VAPJjto+KjN3DKKPlA=");

        local padding = ZeroPadding;

        local decipher = decipher()
                    .setKey(key)
                    .setBlockCipher(AES128Cipher)
                    .setPadding(padding);

        local plainOutput = decipher
                    .init()
                    .update(Stream.fromArray(iv))
                    .update(Stream.fromArray(ciphertext))
                    .finish()
                    .asHex();

plainOutput is 87B1AD89AC65AB0CDD97C981EC810B9410101010101010101010101010101010,actually i want the result is 87B1AD89AC65AB0CDD97C981EC810B941 what can i do?

somesocks commented 7 years ago

Hi zk0318,

Most padding standards require that you always add a padding block. There's a little debate as to whether you should do the same with zero padding, but I decided to make the ZeroPadding behavior the as the other padding schemes.

So, you have two options:

1) If you know the message will always be one block in size, you can just strip the last block 87B1AD89AC65AB0CDD97C981EC810B9410101010101010101010101010101010 87B1AD89AC65AB0CDD97C981EC810B941 ^ just remove this last block ^

But, this only works if you know what the length of the plaintext is.

2) If you don't know how long the message will be, you should use PKCS7 padding instead of zero padding. You should use PKCS7, because the padding bytes tell you how many padding bytes there are. The padding for PKCS7 looks like:

01 02 02 03 03 03 ...

So, if you use PKCS7 padding, after you decypher the message, look at the last byte of the plaintext, and that will tell you how many bytes of padding there are, i.e. how many bytes you need to strip off the end to get the original message.

Hope this helps!