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 Encryption Example

by Khaleel O.
June 16, 2021
in Python
Reading Time: 6 mins read
A A
python aes encryption example
Python AES Encryption Example

We will be using Python 3.8.10 for this Python AES Encryption Example.

AES (Advanced Encryption Standard) was originally called Rijndael and is a symmetric block algorithm for encrypting or decrypting data. The standard was established by the U.S. National Institute of Standards and Technology (NIST) in 2001.

AES has a fixed block size of 128 bits (16 bytes) and has three different key lengths: 128, 192, or 256 bits long.

We will use pycryptodome, which will allow us to encrypt some data using AES-128, save it to a file, reread the same data and decrypt it. First we install the python package before we proceed to our python AES encryption example code:

pip install pycryptodomex

AES Encryption of data in Python can be done in 3 simple steps:

  1. Generate a 128, 192, or 256 bit key.
  2. Use the key to generate the AES cipher
  3. Use the cipher to encrypt the data.

Similarly, AES Decryption of data in Python can be done in 3 simple steps:

  1. Generate a 128, 192, or 256 bit key.
  2. Use the key to generate the AES cipher
  3. Use the cipher to decrypt the data.

Now we write our code to encrypt the data.

from Cryptodome.Cipher import AES
from Cryptodome.Random import get_random_bytes

data=b"SECRETDATA"
key = get_random_bytes(16) #must be 16, 24 or 32 bytes long
cipher = AES.new(key, AES.MODE_EAX)
ciphertext, tag = cipher.encrypt_and_digest(data)

file_out = open("encryptedfile.bin", "wb")
[ file_out.write(x) for x in (cipher.nonce, tag, ciphertext) ]
file_out.close()

Let’s explain what’s going on here:

1.) First, we import our library/modules Cryptodome.Cipher and Cryptodome.Random.

2.) Next, we define our data. The data in this case must be in byte form, hence the b”SECRETDATA”.  Byte literals are always prefixed with ‘b’ or ‘B’.

3.) get_random_bytes returns a random byte string of length N. N in this case is 16 bytes (128 bits) and it must be 16, 24 or 32 bytes long. This is our key.

4.) We use AES.new() to create our cipher. It takes 2 arguments: the key in bytes, which we defined with the previous statement, and the mode which is a constant. In this case we use MODE_EAX. EAX means encrypt-then-authenticate-then-translate and is a mode of opertion for cryptographic block ciphers.

5.) encrypt_and_digest() performs encryption and digest. Recall that encryption conceals the contents of our data, while a digest is a fixed size numeric representation which acts as an identifier for the contents of the data. The encrypt_and_digest method accepts our data and returns a tuple with the ciphertext and the message authentication code (MAC), sometimes known as a tag, which confirms the authenticity and authority of the data.

6.) Finally, we write our encrypted message as ciphertext to the encryptedfile.bin file on disk (same directory as python script) along with the tag and a cipher.nonce. The cipher.nonce is an arbitrary value used only once to ensure that our data is original. If, for example, we see a cipher.nonce used more than once for different pieces of data, we know that security was compromised.

The next step would obviously be to decrypt the data.

file_in = open("encryptedfile.bin", "rb")
nonce, tag, ciphertext = [ file_in.read(x) for x in (16, 16, -1) ]

# the person decrypting the message will need access to the key
cipher = AES.new(key, AES.MODE_EAX, nonce)
data = cipher.decrypt_and_verify(ciphertext, tag)
print(data.decode('UTF-8')) 

Let’s explain what’s going on here.

1.) Anyone who needs to decrypt our message would need access to the file to read in the bytes. Once we do that, we will retrieve the nonce, tag and ciphertext.

2.) We use AES.new() to create our cipher, as we did before but this time we include our nonce. Normally only the person decrypting the message should have access to the key.

3.) We call decrypt_and_verify, pass the ciphertext and tag and our decrypted data is returned to us. Yaaaay!

4.) Our data is in bytes so we must use method decode before we can use print() to show us the message in the console.

Below is our full code:

from Cryptodome.Cipher import AES
from Cryptodome.Random import get_random_bytes

#define our data
data=b"SECRETDATA"

key = get_random_bytes(16)
cipher = AES.new(key, AES.MODE_EAX)
ciphertext, tag = cipher.encrypt_and_digest(data)

file_out = open("encryptedfile.bin", "wb")
[ file_out.write(x) for x in (cipher.nonce, tag, ciphertext) ]
file_out.close()

#################################################################

file_in = open("encryptedfile.bin", "rb")
nonce, tag, ciphertext = [ file_in.read(x) for x in (16, 16, -1) ]

#the person decrypting the message will need access to the key
cipher = AES.new(key, AES.MODE_EAX, nonce)
data = cipher.decrypt_and_verify(ciphertext, tag)
print(data.decode('UTF-8')) 

#output:
#SECRETDATA

We hope that helped! AES encryption has many applications including file and storage encryption, communications encryption and passwords just to name a few. Find out more about it HERE.

Thanks for reading. 👌👌👌

Tags: Python AES Encryption Example
Previous Post

Formatted String In Python 3 – Part 2

Next Post

Python AES 256 Encryption 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