3
$\begingroup$

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 ?

$\endgroup$
1
  • 1
    $\begingroup$ I love this question, because I've seen this in a CTF once and used the base idea as an exam question. $\endgroup$
    – tistorm
    Commented Aug 27, 2023 at 23:27

1 Answer 1

3
$\begingroup$

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.

$\endgroup$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.