Using the PyCryptodome module in Python, we can perform AES encryption and decryption very easily. AES is a block cipher. So, the input plaintext is divided into blocks and then padded. We perform encryption operation on the padded plaintext bytes. Similarly, after the decryption operation, we get padded decrypted bytes. We need to unpad the decrypted bytes to get the plaintext.
import os from Crypto.Util.Padding import pad, unpad from Crypto.Cipher import AES def getKey(keysize): key = os.urandom(keysize) return key def getIV(blocksize): iv = os.urandom(blocksize) return iv KEYSIZE = 16 BLOCKSIZE = 16 plaintext1 = "Hello! Welcome to The Security Buddy!!" key = getKey(KEYSIZE) iv = getIV(BLOCKSIZE) cipher1 = AES.new(key, AES.MODE_CBC, iv) ciphertext = cipher1.encrypt(pad(plaintext1.encode(), BLOCKSIZE)) print(ciphertext) cipher2 = AES.new(key, AES.MODE_CBC, iv) plaintext2 = unpad(cipher2.decrypt(ciphertext), BLOCKSIZE) print(plaintext2.decode())
Using the above program, we can perform AES encryption and decryption using the CBC mode. To encrypt a block of plaintext in this mode, we need to provide an Initialization Vector (IV) and a key.
In this program, we are performing AES-128 encryption and decryption. So, the blocksize is 128-bit or 16-byte. And, the size of the key is also 128-bit or 16-byte. The size of the initialization vector is equal to …
0 Comments