Using AES for Encryption and Decryption in Python Pycrypto (2024)

Easily incorporate strong AES encryption into your programs.

“Believe in your infinite potential. Your only limitations are those you set upon yourself.” ― Roy T. Bennett, The Light in the Heart

Contents

  • 1. Introduction
  • 2. Generating a Key
  • 3. Initialization Vector
  • 4. Encrypting with AES
  • 5. Decrypting with AES
  • 6. File Encryption with AES
    • 6.1. Write the Size of the File
    • 6.2. Save the Initialization Vector
    • 6.3. Adjust Last Block
  • 7. Decrypting File Using AES
  • Conclusion
    • See Also

1. Introduction

Pycrypto is a python module that provides cryptographic services. Pycrypto is somewhat similar to JCE (Java Cryptography Extension) for Java. In our experience JCE is more extensive and complete, and the documentation for JCE is also more complete. That being said, pycrypto is a pretty good module covering many aspects of cryptography.

In this article, we investigate using pycrypto’s implementation of AES for file encryption and decryption.

[Note: We have also covered AES file encryption and decryption in java previously.]

2. Generating a Key

AES encryption needs a strong key. The stronger the key, the stronger your encryption. This is probably the weakest link in the chain. By strong, we mean not easily guessed and has sufficient entropy (or secure randomness).

That being said, for the sake of demonstration of AES encryption, we generate a random key using a rather simple scheme. Do not copy and use this key generation scheme in production code.

AES encryption needs a 16-byte key.

key = ''.join(chr(random.randint(0, 0xFF)) for i in range(16))print 'key', [x for x in key]# printskey ['+', 'Y', '\xd1', '\x9d', '\xa0', '\xb5', '\x02', '\xbf', ';', '\x15', '\xef', '\xd5', '}', '\t', ']', '9']

3. Initialization Vector

In addition to the key, AES also needs an initialization vector. This initialization vector is generated with every encryption, and its purpose is to produce different encrypted data so that an attacker cannot use cryptanalysis to infer key data or message data.

A 16-byte initialization vector is required which is generated as follows.

iv = ''.join([chr(random.randint(0, 0xFF)) for i in range(16)])

The initialization vector must be transmitted to the receiver for proper decryption, but it need not be kept secret. It is packed into the output file at the beginning (after 8 bytes of the original file size), so the receiver can read it before decrypting the actual data.

4. Encrypting with AES

We now create the AES cipher and use it for encrypting a string (or a set of bytes; the data need not be text only).

The AES cipher is created with CBC Mode wherein each block is “chained” to the previous block in the stream. (You do not need to know the exact details unless you are interested. All you need to know is – use CBC mode).

Also, for AES encryption using pycrypto, you need to ensure that the data is a multiple of 16-bytes in length. Pad the buffer if it is not and include the size of the data at the beginning of the output, so the receiver can decrypt properly.

aes = AES.new(key, AES.MODE_CBC, iv)data = 'hello world 1234' # <- 16 bytesencd = aes.encrypt(data)

5. Decrypting with AES

Decryption requires the key that the data was encrypted with. You need to send the key to the receiver using a secure channel (not covered here).

In addition to the key, the receiver also needs the initialization vector. This can be communicated as plain text, no need for encryption here. One way to send this is to include it in the encrypted file, at the start, in plaintext form. We demonstrate this technique below (under File Encryption with AES). For now, we assume that the IV is available.

aes = AES.new(key, AES.MODE_CBC, iv)decd = adec.decrypt(encd)print decd# printshello world 1234

And that is how simple it is. Now read on to know how to encrypt files properly.

6. File Encryption with AES

We have three issues to consider when encrypting files using AES. We explain them in detail below.

First step is to create the encryption cipher.

aes = AES.new(key, AES.MODE_CBC, iv)

6.1. Write the Size of the File

First we have to write the size of the file being encrypted to the output. This is required to remove any padding applied to the data while encrypting (check code below).

Determine the size of the file.

fsz = os.path.getsize(infile)

Open the output file and write the size of the file. We use the struct package for the purpose.

with open(encfile, 'w') as fout: fout.write(struct.pack('<Q', fsz))

6.2. Save the Initialization Vector

As explained above, the receiver needs the initialization vector. Write the initialization vector to the output, again in clear text.

 fout.write(iv)

6.3. Adjust Last Block

The third issue is that AES encryption requires that each block being written be a multiple of 16 bytes in size. So we read, encrypt and write the data in chunks. The chunk size is required to be a multiple of 16.

sz = 2048

This means the last block written might require some padding applied to it. This is the reason why the file size needs to be stored in the output.

Here is the complete write code.

 with open(infile) as fin: while True: data = fin.read(sz) n = len(data) if n == 0: break elif n % 16 != 0: data += ' ' * (16 - n % 16) # <- padded with spaces encd = aes.encrypt(data) fout.write(encd)

7. Decrypting File Using AES

Now we need to reverse the above process to decrypt the file using AES.

First, open the encrypted file and read the file size and the initialization vector. The IV is required for creating the cipher.

with open(encfile) as fin: fsz = struct.unpack('<Q', fin.read(struct.calcsize('<Q')))[0] iv = fin.read(16)

Next create the cipher using the key and the IV. We assume the key has been communicated using some other secure channel.

 aes = AES.new(key, AES.MODE_CBC, iv)

We also write the decrypted data to a “verification file”, so we can check the results of the encryption and decryption by comparing with the original file.

 with open(verfile, 'w') as fout: while True: data = fin.read(sz) n = len(data) if n == 0: break decd = aes.decrypt(data) n = len(decd) if fsz > n: fout.write(decd) else: fout.write(decd[:fsz]) # <- remove padding on last block fsz -= n

Note that when the last block is read and decrypted, we need to remove the padding (if any has been applied). This is where we need the original file size.

Conclusion

And that is all there is to encrypting and decrypting a file using AES in python. We need to generate or obtain a key, create the initialization vector and write the original file size followed by the IV into the output file. This is followed by the encrypted data. Finally decryption does the same process in reverse.

See Also

Using AES for Encryption and Decryption in Python Pycrypto (2024)

FAQs

How to do AES encryption and decryption in Python? ›

How to encrypt and decrypt text using AES in python?
  1. Process. Get the input message text. In AES the same key used for both encryption and decryption. Generate the secret key. Define the mode of AES. ...
  2. Sample Code. #import crypto and base64. from Crypto.Cipher import AES. import base64. message = ...
  3. Screenshots.

How hard is it to decrypt AES? ›

AES-256 encryption is virtually uncrackable using any brute-force method. It would take millions of years to break it using the current computing technology and capabilities.

Which algorithm is best for encryption and decryption in Python? ›

Some of the most common and widely used algorithms are AES, RSA, and Fernet. AES is a symmetric algorithm that uses the same key for encryption and decryption, and it is fast and efficient for large data.

How long does it take to decrypt AES? ›

If you ask how long will it take to crack 128-bit encryption using a brute force attack, the answer would be 1 billion years. A machine that can crack a DES key in a second would take 149 trillion years to crack a 128-bit AES key.

What is the difference between AES encryption and AES decryption? ›

The AES algorithm is a symmetrical block cipher that encrypts and decrypts data in blocks of 256 bits. The decryption block uses the AES algorithm to decrypt the boot loader image and configuration data before configuring the FPGA portion of the device. If encryption is not used, the AES decryptor is bypassed.

How to generate AES 256 key in Python? ›

Explanation
  1. The AES key is generated by the Scrypt key derivation algorithm using the password and a random 32 bytes salt.
  2. The password is hashed using SHA3-512 with the same salt than the AES-256 key.
  3. Salt, hashed password and the initialisation vector are stored at the beginning of the new encrypted file.

Can I decrypt AES without a key? ›

If its encrypted, the only way to get the contents without the encryption key is to brute-force it, but I wouldn't get your hopes up. All these malware variants as of late rely on encryption being nearly unbreakable without government-funded super computing power, and even then its time consuming.

Is AES still the best encryption? ›

Because of its key length options, AES encryption remains the best choice for securing communications.

What is the hardest code to decrypt? ›

The Vigenère cipher is a method of encrypting messages by using a series of different Caesar ciphers based on the letters of a particular keyword. The Vigenère cipher is more powerful than a single Caesar cipher and is much harder to crack.

What is the strongest encryption algorithm in the world? ›

AES 256-bit encryption is the strongest and most robust encryption standard that is commercially available today. While it is theoretically true that AES 256-bit encryption is harder to crack than AES 128-bit encryption, AES 128-bit encryption has never been cracked.

What type of encryption does Python use? ›

Python has a cryptography library with which you can encrypt and decrypt your files. This library implements the AES symmetric encryption algorithm and uses the same key to encrypt and decrypt data. The methods that implement the encryption algorithm are in the Fernet module.

What is the best password encryption algorithm in Python? ›

There are many types of hash algorithms but SHA-256 is a strong and NIST Approved modern algorithm that fits the need of most applications in terms of strength and performance. Create a simple Python script file to take an input and generate the SHA-256 hash with the hashlib standard library.

Should I use AES-128 or 256? ›

Our best guidance is that AES-128 provides more than adequate security while being faster and more resource-efficient but readers who want that extra security provided by greater key sizes and more rounds in the algorithm should choose AES-256.

How strong is AES encryption? ›

It's virtually impossible to break AES-256 through brute force attacks, no matter how powerful the computer(s) involved in the process.

Why is AES encryption faster than decryption? ›

For example, while DES uses 64-bit blocks, AES encrypts data in 128-bit blocks. AES also handles this encryption at the byte level rather than bit level. A byte is eight bits, so this results in faster encryption and decryption times when the proper key is applied. Another strength of AES is its variable key length.

How to decrypt AES encryption file? ›

Decrypting a file
  1. In File Explorer, right-click the file you want to decrypt (it always ends in “. aes”).
  2. Choose “AES Decrypt” from the context menu.
  3. Enter the password.
  4. The file will be opened.

How to encrypt data using AES encryption? ›

The first step of AES 256 encryption is dividing the information into blocks. Because AES has a 128- bits block size, it divides the information into 4x4 columns of 16 bytes. The next step of AES 256 encryption involves the AES algorithm recreating multiple round keys from the first key using Rijndael's key schedule.

How do I set AES encryption? ›

Configure the AES 256-bit encryption key
  1. Load required key pairs and certificates for Code Signing.
  2. Prepare Circle of Trust certificates.
  3. Import and install certificates for Circle of Trust.
  4. Turn on Code Signing.
  5. Create Code Signing key pairs and certificates.
  6. Specify custom rules in ECC firewall.

What are the steps in AES decryption algorithm? ›

Similarly, AES decryption consists of 5 part: KeyExpansion, Inverse SubBytes, Inverse ShiftRows, Inverse MixColumns and AddRoundKey. KeyExpansion also generates 11/13/15 round keys from input cipher key and they maps to 2-D array as states do.

Top Articles
What Is the Best Stablecoin? 8 Top Stablecoins to Buy in 2024
How Much of Your Paycheck Should You Save?
Xre-02022
Dairy Queen Lobby Hours
The Largest Banks - ​​How to Transfer Money With Only Card Number and CVV (2024)
What spices do Germans cook with?
Obor Guide Osrs
The Powers Below Drop Rate
Big Y Digital Coupon App
Giovanna Ewbank Nua
Baseball-Reference Com
Knaben Pirate Download
Regal Stone Pokemon Gaia
Pvschools Infinite Campus
Palm Coast Permits Online
Uky Linkblue Login
Adam4Adam Discount Codes
Directions To Advance Auto
Indystar Obits
Walgreens Alma School And Dynamite
Acts 16 Nkjv
Heart Ring Worth Aj
Bible Gateway passage: Revelation 3 - New Living Translation
Stihl Dealer Albuquerque
Boxer Puppies For Sale In Amish Country Ohio
Robotization Deviantart
Abga Gestation Calculator
Maths Open Ref
Dl.high Stakes Sweeps Download
Tripcheck Oregon Map
Syracuse Jr High Home Page
Devargasfuneral
Capital Hall 6 Base Layout
Here’s how you can get a foot detox at home!
Drabcoplex Fishing Lure
PA lawmakers push to restore Medicaid dental benefits for adults
Bimar Produkte Test & Vergleich 09/2024 » GUT bis SEHR GUT
The Bold And The Beautiful Recaps Soap Central
Ticketmaster Lion King Chicago
Anhedönia Last Name Origin
Xxn Abbreviation List 2023
5A Division 1 Playoff Bracket
Tricia Vacanti Obituary
Tinfoil Unable To Start Software 2022
Craigslist/Nashville
Theater X Orange Heights Florida
Lesly Center Tiraj Rapid
Myra's Floral Princeton Wv
Is Chanel West Coast Pregnant Due Date
Autozone Battery Hold Down
Craigslist Centre Alabama
What Are Routing Numbers And How Do You Find Them? | MoneyTransfers.com
Latest Posts
Article information

Author: Kimberely Baumbach CPA

Last Updated:

Views: 5782

Rating: 4 / 5 (41 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Kimberely Baumbach CPA

Birthday: 1996-01-14

Address: 8381 Boyce Course, Imeldachester, ND 74681

Phone: +3571286597580

Job: Product Banking Analyst

Hobby: Cosplaying, Inline skating, Amateur radio, Baton twirling, Mountaineering, Flying, Archery

Introduction: My name is Kimberely Baumbach CPA, I am a gorgeous, bright, charming, encouraging, zealous, lively, good person who loves writing and wants to share my knowledge and understanding with you.