No Result
View All Result
DevRescue
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us
DevRescue
Home Blog Python

Python AES CBC Encrypt Example

by Khaleel O.
July 16, 2022
in Python
Reading Time: 3 mins read
A A
python aes cbc encrypt
python aes cbc encrypt

Let’s do a Python AES CBC Mode Encrypt example. Python 3.8.10 will be used.

AES (Advanced Encryption Standard) is a method of data encryption established in 2001. It is a block cipher and uses a symmetric-key algorithm, which means the same key is used for both encryption and decryption of the data.

CBC (Cipher Block Chaining) is a mode of operation of AES whose strength lies in its ability to reliably obfuscate patterns in the plaintext. To achieve this, an initialization vector or iv is used in the first block and each subsequent block of plaintext is “XOR’d” with the previous block of ciphertext before being encrypted. This makes each ciphertext block dependent on the chain of processed plaintext blocks that came before it. Recall that XOR or Exclusive Or is a logical operation that is true only if the arguments are different.

First, let’s import the library to be used, pycryptodome:

pip install pycryptodomex

Now, let’s write our code:

from base64 import b64encode
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
from Crypto.Random import get_random_bytes

sensitive_data = b"ALIENS DO EXIST!!!!"
key = get_random_bytes(16) #must be 16, 24 or 32 bytes long
cipher = AES.new(key, AES.MODE_CBC)
ciphertext = cipher.encrypt(pad(sensitive_data, AES.block_size))

print(f"iv: {b64encode(cipher.iv).decode('utf-8')}")
print(f"ciphertext:{b64encode(ciphertext).decode('utf-8')}")
print(f"key: {b64encode(key).decode('utf-8')}")

#Sample output
#iv: V3/oW179L1BRtRP11Nfc/w==
#ciphertext:0W6tw7CduTlymN8tOeWAL4UhCuu0ItyV7oZ7q3JWx3k=
#key: jbFlVdSLxI7kWkQTTjvoyQ==

Let’s explain what is happening here:

  1. We import the libraries we will need.
  2. We define the data to be encrypted as sensitive_data. This is the plaintext.
  3. The key is the user defined value required by the AES cipher to encrypt the data and it must be 16, 24 or 32 bytes long. Because AES uses the symmetric-key algorithm both the encryption and decryption key is the same. The key must be kept secret.
  4. The variable cipher is a CBC Cipher object. It is the return value of the AES.new() method which accepts the key and the AES encryption mode which, for the CBC method, must be MODE_CBC.
  5. The variable ciphertext is the encrypted plaintext. The method cipher.encrypt() accepts the sensitive_data to be encrypted as a parameter, but it expects the data to have a length that is a multiple of the AES.block_size which is 16 bytes. To achieve that, we pass the block size and data to the pad() function which pads the data if needed to ensure that it is a multiple of the block size, else the cipher will return an error.
  6. The iv is the initialization vector that is needed by the AES algorithm. It is the same length as the block size. If one is not explicitly provided a random iv will be generated, as it was in this case. The actual value is accessible by using the built in variable cipher.iv

When the above code executes you will see three values on the terminal/console/command line: the iv or initialization vector, the ciphertext and the key. Each values is encoded in base64 to make it readable. Be sure to take note of these 3 values because they will be needed for the DECRYPTION tutorial.

The next step would be to DECRYPT this data, which we will do in PART 2 of this tutorial.

Thanks for reading!👌👌👌

Tags: encryption
Previous Post

Webpage Screenshot with Python

Next Post

Python AES CBC Decrypt Example

Khaleel O.

Khaleel O.

I love to share, educate and help developers. I have 14+ years experience in IT. Currently transitioning from Systems Administration to DevOps. Avid reader, intellectual and dreamer. Enter Freely, Go safely, And leave something of the happiness you bring.

Related Posts

Python

Python Fibonacci Recursive Solution

by Khaleel O.
January 16, 2024
0
0

Let's do a Python Fibonacci Recursive Solution. Let's go! 🔥🔥🔥 The Fibonacci sequence is a series of numbers in which...

Read moreDetails
Python

Python Slice String List Tuple

by Khaleel O.
January 16, 2024
0
0

Let's do a Python Slice string list tuple how-to tutorial. Let's go! 🔥🔥🔥 In Python, a slice is a feature...

Read moreDetails
Python

Python Blowfish Encryption Example

by Khaleel O.
January 14, 2024
0
0

Let's do a Python Blowfish Encryption example. Let's go! 🔥 🔥 Blowfish is a symmetric-key block cipher algorithm designed for...

Read moreDetails
Python

Python Deque Methods

by Khaleel O.
January 14, 2024
0
0

In this post we'll list Python Deque Methods. Ready? Let's go! 🔥🔥🔥 A deque (double-ended queue) in Python is a...

Read moreDetails

DevRescue © 2021 All Rights Reserved. Privacy Policy. Cookie Policy

Manage your privacy

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Statistics

Marketing

Features
Always active

Always active
  • Manage options
  • Manage services
  • Manage {vendor_count} vendors
  • Read more about these purposes
Manage options
  • {title}
  • {title}
  • {title}
Manage your privacy
To provide the best experiences, DevRescue.com will use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Statistics

Marketing

Features
Always active

Always active
  • Manage options
  • Manage services
  • Manage {vendor_count} vendors
  • Read more about these purposes
Manage options
  • {title}
  • {title}
  • {title}
No Result
View All Result
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us

DevRescue © 2022 All Rights Reserved Privacy Policy