If we want to encrypt plaintext using a block cipher like AES, we need to ensure that the input bytes are multiple of blocksize in size and they are padded. We can use pad and unpad methods from Crypto.Util.Padding for this purpose. But, if we want to implement PKCS#7 padding and unpadding in Python, how can we do so? In this article, we would discuss that in detail.
In our previous article, we have discussed how to perform AES encryption and decryption using the PyCryptodome module in Python. We used plaintext1 = “Hello! Welcome to The Security Buddy!!” which is more than 16 bytes in size. We padded the plaintext bytes to ensure the plaintext bytes are multiple of 16 bytes in size and padded. After that, we performed the AES-128 encryption operation on the padded bytes.
ciphertext = cipher1.encrypt(pad(plaintext1.encode(), BLOCKSIZE))
Similarly, after the decryption operation, we got decrypted bytes that are multiple of 16 bytes in size. We used the unpad function from Crypto.Util.Padding to get the unpadded bytes. Then, we decoded the unpadded decrypted bytes to get the plaintext.
plaintext2 = unpad(cipher2.decrypt(ciphertext), BLOCKSIZE) print(plaintext2.decode())
In this article, we would discuss how PKCS#7 padding works and how to implement the PKCS#7 pad and unpad functions in Python.
In this article, we will discuss:
-
How does the PKCS#7 padding work?
-
How to implement PKCS#7 padding and unpadding in Python?
0 Comments