Let’s do a Python AES CBC Decrypt tutorial! If you haven’t already done so, please check out PART 1 of this tutorial where we encrypted data using the AES CBC mode.
To proceed, you MUST have access to the generated ciphertext, iv and key values from PART 1 of this tutorial.
Now, let’s write our code:
from base64 import b64decode
from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad
try:
iv = b64decode('V3/oW179L1BRtRP11Nfc/w==')
ciphertext = b64decode('0W6tw7CduTlymN8tOeWAL4UhCuu0ItyV7oZ7q3JWx3k=')
key = b64decode('jbFlVdSLxI7kWkQTTjvoyQ==')
cipher = AES.new(key, AES.MODE_CBC, iv)
plaintext = unpad(cipher.decrypt(ciphertext), AES.block_size)
print("Original Message was: ", plaintext)
except (ValueError, KeyError):
print("ERROR!")
#Sample output
#Original Message was: b'ALIENS DO EXIST!!!!'
Let’s explain what is happening here:
- We import the libraries needed. Be sure that the Pycryptodome library is installed with the following command: pip install pycryptodomex.
- We nest the decryption operation in a try…catch block.
- We supply the iv or initialization vector, the ciphertext and the key. All values acquired from the encrypt operation. The bytes are encoded in base64 format to make them readable so we must invoke b64decode() to revert them to bytes.
- The cipher object that is used to decrypt the data is defined using the AES.new() method, which expects the key, the mode which is MODE_CBC and the iv.
- If the original ciphertext was padded so that it would be a multiple of the block size (16 bytes for AES) then it has to be unpadded, hence the call to unpad(). Only after the ciphertext is decrypted can unpadding take place, if needed.
If all goes well you should see the original message that was encrypted from the PART 1 tutorial, now printed on the console/terminal/command line in readable letters. If not, please ensure that you copied the correct ciphertext, key and iv from the PART 1 Encryption tutorial.
That was fun wasn’t it? Thanks for reading. 👌👌👌
Are you worried about your child’s online safety or your employees’ productivity? Do you wonder what they’re accessing on their devices? SentryPC is here to address these concerns. This all-in-one, cloud-based software provides robust activity monitoring, content filtering, and time management, making it ideal for both parental control and employee monitoring. Embrace peace of mind and enhanced efficiency with SentryPC, the proactive solution to your digital monitoring needs. CLICK HERE to get started.