Need to encrypt some text with a password or private key in Python? AES-256 is a solid symmetric cipher that is commonly used to encrypt data for oneself. In other words, the same person who is encrypting the data is typically decrypting it as well (think password manager).

Before we dive in, if you’re here because you’re interested in learning cryptography in a more comprehensive and structured way, I recently released a free hands-on coding course, Practical Cryptography, where you can do so.

Dependencies

For this tutorial, we’ll be using Python 3, so make sure you install pycryptodome, which will give us access to an implementation of AES-256:

Padding – Handled by GCM

AES-256 typically requires that the data to be encrypted is supplied in 16-byte blocks, and you may have seen that on other sites or tutorials. AES-256 in GCM mode, however, doesn’t require any special padding to be done by us manually.

Encrypting

Now we create a simple encrypt(plain_text, password) function. This function uses the password to encrypt the plain text. Therefore, anyone with access to the encrypted text and the password will be able to decrypt it.

Generate

Notes on encrypt() function

  1. Nonce: A random nonce (arbitrary value) must be a random and unique value for each time our encryption function is used with the same key. Think of it as a random salt for a cipher. The library supplies us with a secure nonce.
  2. Scrypt: Scrypt is used to generate a secure private key from the password. This will make it harder for an attacker to brute-force our encryption.
  3. Salt: A new random salt is used for each run of our encryption. This makes it impossible for an attacker to use precomputed hashes in an attempt to crack the cipher. (see rainbow table)
  4. Scrypt parameters:
    1. N is the cost factor. It must be a power of two, and the higher it is the more secure the key, but the more resources it requires to run.
    2. R is the block size.
    3. P is the parallelization factor, useful for running on multiple cores.
  5. Base64: We encode all of our bytes-type data into base64 a convenient string representation
  6. Tag (MAC): The tag is used to authenticate the data when using AES in GCM mode. This ensures no one can change our data without us knowing about it when we decrypt.

Generate Aes 256 Key Python 3

We use AES in a mode of operation in order to encrypt. The solutions above suggest using CBC, which is one example. Another is called CTR, and it’s somewhat easier to use: # AES supports multiple key sizes: 16 (AES128), 24 (AES192), or 32 (AES256). # pair (iv, ciphtertext). 'iv' stands for initialization vector. Edit 2015.12.14: thanks to Stephen for pointing out that the block size for AES is always 16, and the key size can be 16, 24, or 32. See FIPS-197 for more details. If you plan to use this script, you'll need to have PyCrypto installed on your computer. You may also want to check out all available functions/classes of the module Crypto.Cipher.AES, or try the search function. Project: file-encryptor Author: StorjOld File: convergence.py License: MIT License. Def itertransform(filename, key): 'Generate encrypted file with given key. This generator function reads the file.

Decrypting

Notes on decrypt() function

  1. The decrypt() function needs the same salt, nonce, and tag that we used for encryption. We used a dictionary for convenience in parsing, but if we instead wanted one string of ciphertext we could have used a scheme like salt.nonce.tag.cipher_text
  2. The configuration parameters on the Scrypt and AES functions need to be the same as the encrypt function.

Give Me The Full Code!

You probably want to see it all work in an example script. Look no further!

Thanks for reading, now take a course!

Interested in a high-paying job in tech? Land interviews and pass them with flying colors after taking my hands-on coding courses.

Questions?

Follow and hit me up on Twitter @q_vault if you have any questions or comments. If I’ve made a mistake in the article be sure to let me know so I can get it corrected!

Subscribe to my newsletter for more coding articles delivered straight to your inbox.

Related Reading

AWS Boto3 is the Python SDK for AWS. Boto3 can be used to directly interact with AWS resources from Python scripts. In this tutorial, we will look at how we can use the Boto3 library to perform various operations on AWS KMS.

Table of contents

Prerequisites

  • Python3
  • Boto3: Boto3 can be installed using pip:pip install boto3
  • AWS Credentials: If you haven’t set up AWS credentials before, this resource from AWS is helpful.
  • cryptopgraphy: We will be using the cryptography package to encrypt and decrypt data.

How to create a Customer Master Key?

A Customer Master Key (CMK) is used to encrypt data. However, the maximum size of data that can be encrypted using the master key is 4KB. CMKs are used to generate, encrypt, and decrypt data keys that can be used outside of AWS KMS to encrypt data.

Generate Aes 256 Key PythonGenerate

AWS KMS supports two types of CMKs:

  • Symmetric CMK: 256-bit symmetric key that never leaves AWS KMS unencrypted By default, KMS creates a symmetric CMK.
  • Asymmetric CMK: AWS KMS generates a key pair where private key never leaves AWS KMS unencrypted.

The following function creates a new Customer Master Key:

The output of the above function should be something like:

How to retrieve existing Customer Master Key?

CMKs are created, managed and stored within AWS KMS. The following snippet shows how to retrieve an existing CMK based on the description it was created with.

Output

How to create a data key?

A data key is a unique symmetric data key that is used to encrypt data outside of AWS KMS. AWS returns both an encrypted and a plaintextversion of the data key.

AWS recommends the following pattern to use the data key to encrypt data outside of AWS KMS:

The function below generates a data key and returns the encrypted as well as plaintext copy of the key.

How to encrypt data?

Data can be encrypted client-side using the generated data key along with the cryptography package in Python. It is recommended to store the encrypted data key along with your encrypted data since that will be used to decrypt the data in the future.

Next, let’s create a file called test_file with the following content:

After running the encrypt_file function on our input file, the contents of the encrypted file should look something like:

How to decrypt a data key?

The decrypt function can be used to decrypt an encrypted data key. The decrypted data key can then be used to decrypt any data on the client side.

How to decrypt data?

Generate aes 256 key python

Generate Aes 256 Key Python Download

Output of running this function on the encrypted file: