the blocksize, which is 128-bit.
So, we are firstly generating the key and the IV randomly. We are using os.urandom() method for this purpose. This method takes as input the size in bytes. And, it generates the bytes randomly. The os.urandom() method can generate random bytes that are cryptographically secure. (What is entropy in cryptography?)
After generating the key and the iv, we are initializing the cipher using the AES.new() method. This function takes as input the key and the AES mode. As we are using the CBC mode, we need to also provide the initialization vector as an input to the AES.new() function.
Please note that our plaintext is “Hello! Welcome to The Security Buddy!!” which is more than 16 bytes. So, the plaintext will be divided into 16-byte blocks and the last block should be padded. We are using the pad() method from Crypto.Util.Padding for this purpose. This function takes the input bytes and blocksize as input and returns the padded bytes. Please note that this method does a PKCS#7 padding.
Moreover, as the pad() function takes bytes as input, we are encoding the plaintext using the encode() method and providing the returned bytes as input.
Please note that if we do not pad the plaintext and instead use “ciphertext = cipher1.encrypt(plaintext1.encode())”, then the program will give an error “Data must be padded to 16-byte boundary in CBC mode”
So, after padding the plaintext, we get padded data which is multiple of 16 bytes. We can now use the bytes as input to cipher1.encrypt() function.
The decryption operation can be performed similarly. We need to initialize the cipher, in the same way, using the same key and the initialization vector. After the initialization, we can use cipher2.decrypt(ciphertext) function to generate decrypted bytes.
Please note that we get decrypted bytes that are multiple of 16 bytes in size and padded. So, we need to first remove the padding and then decode() the bytes to get the plaintext.
We are using the unpad() function from Crypto.Util.Padding for this purpose. And, then we are decoding the unpadded bytes to get the plaintext. (How to implement the PKCS#7 pad and unpad functions in Python?)
I hope this helps. However, readers who want to know more about how different cryptographic algorithms work and how they are used in various secure network protocols can refer to the book “Cryptography And Public Key Infrastructure.”










































0 Comments