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

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

We will be using Python 3.8.10 for this Python AES 256 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.

For this tutorial we will be using the pycryptodome library/module, which we can install with the following command at the terminal (if you don’t have it already):

pip install pycryptodomex

3 simple steps to use AES 256 bit encryption in Python:

  1. Generate a 256bit encryption key
  2. Use the key to create a cipher
  3. Encrypt the data with the cipher

Now let’s write our code.


First, let’s encrypt our data:

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

data=b"DATA_TO_BE_ENCRYPTED"
password=b"PASSWORD"
salt = get_random_bytes(32)

key = hashlib.scrypt(password, salt=salt, n=2**14, r=8, p=1, dklen=32)
cipher = AES.new(key, AES.MODE_GCM)
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 is going on here:

  1. We import all the modules we will use.
  2. We have our data and password. Byte literals are always prefixed with ‘b’ or ‘B’.
  3. We generate a salt using get_random_bytes which returns a random byte string of length N. N in this case is 32 bytes (256 bits). The salt is used to provide additional security for our key.
  4. We generate our key using scrypt. This method takes the password, salt, CPU/Memory Cost Factor (n), the block size (r), the parallelization factor (p) and the length of the derived key (dklen). Because we are using AES 256, we must use 32 bytes as the dklen.
  5. We generate our cipher using AES.new(). 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 are using Galois/Counter Mode (GCM) which is a high performance mode.
  6. We call encrypt_and_digest() which 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.
  7. 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.

Now, let’s learn how to decrypt our data. Whoever is going to decrypt and consume our data will need access to the password, the salt, ciphertext, nonce and tag.

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

key = hashlib.scrypt(password, salt=salt, n=2**14, r=8, p=1, dklen=32)
cipher = AES.new(key, AES.MODE_GCM, nonce)
data = cipher.decrypt_and_verify(ciphertext, tag)
print(data.decode('UTF-8')) 

Let’s explain what is happening here:

  1. We access the file with the encrypted data to read in the bytes. Once we do that, we will retrieve the nonce, tag and ciphertext.
  2. We provide our password, the retrieved salt and the other parameters to re-generate our key.
  3. 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.
  4. We call decrypt_and_verify, pass the ciphertext and tag and our decrypted data is returned to us. Yaaaay!
  5. Our data is in bytes so we must use method decode before we can use print() to show us the message in the console.

That’s it! Below is our full working code:

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

data=b"DATA_TO_BE_ENCRYPTED"
password=b"PASSWORD"
salt = get_random_bytes(32)

key = hashlib.scrypt(password, salt=salt, n=2**14, r=8, p=1, dklen=32)
cipher = AES.new(key, AES.MODE_GCM)
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) ]

key = hashlib.scrypt(password, salt=salt, n=2**14, r=8, p=1, dklen=32)
cipher = AES.new(key, AES.MODE_GCM, nonce)
data = cipher.decrypt_and_verify(ciphertext, tag)
print(data.decode('UTF-8')) 

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 256 encryption example
Previous Post

Python AES Encryption Example

Next Post

Python Class Inheritance Examples

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