Score:3

Weird padding in Crypto.Util.Padding.pad() function in python

ws flag

I'm trying to pad some plaintext to be a multiple of 16 bytes to use it as input in AES ECB block cipher.

 def encrypt(plaintext):
    plaintext = bytes.fromhex(plaintext)
    padded = pad(plaintext, 16)
    cipher = AES.new(b'0'*16, AES.MODE_ECB)
    try:
        encrypted = cipher.encrypt(padded)
    except ValueError as e:
        return {"error": str(e)}
    return {"ciphertext": encrypted.hex()}

I understand that AES is a block cipher and it accepts 16byte blocks as input. But what I need to know here is that when I'm actually providing the function with 16byte block, why is it the padding function adding another 16byte block as follows

plain = "123456789abcdefg"
plain = plain.encode("utf-8").hex()
encrypt(plain)
plaintext:  b'123456789abcdefg'
padded:  3132333435363738396162636465666710101010101010101010101010101010

Why does that happen ?

tistorm avatar
ad flag
I love this question, because I've seen this in a CTF once and used the base idea as an exam question.
Score:3
ru flag

In the event that the plaintext is a multiple of the blocksize, PKCS#7 padding specifies that an additional block be added. For 128-bit blocksize, this block is all 0x10 bytes, showing 16 bytes of padding.

The reason from this is to that recipient can distinguish between (for example) a 15-byte message and a 16-byte message with the same leading 15-bytes and final byte 0x01.

I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.