Learn How to Encrypt a Text Message in Python

Two people engaged in phone conversations, depicted with encrypted message texts above their heads symbolizing secure communication. A chain with locks represents encryption, with a Python logo on one lock. The image includes text on the left reading 'Encrypt a Text Message in Python'.

Introduction

Have you ever sent a private message containing sensitive information, like a credit card number or a heartfelt confession? In todayā€™s digital age, where information travels at lightning speed, keeping our personal and confidential data secure is very important.

In this article, you will learn how to encrypt a text in Python. We will use AES-256 encryption, a powerful algorithm used by governments and security experts alike. By the end of this tutorial, youā€™ll be able to encrypt your own text messages, adding an extra layer of protection to your digital communication.

What is the AES algorithm?

The Advanced Encryption Standard (AES) is a widely adopted symmetric-key encryption algorithm established by the National Institute of Standards and Technology (NIST) in 2001. Itā€™s considered one of the most secure block ciphers, meaning it encrypts data in fixed-size blocks.

AES-256 is a specific variant of AES that uses a 256-bit key length that offers a very high level of encryption strength.

How does the AES algorithm work?

AES works by performing a series of operations on blocks of data (128 bits at a time) using a specific key (128, 192, or 256 bits). Hereā€™s a simplified explanation of the process:

  1. Preparation:
    • The plain text (original data) is divided into fixed-size blocks (16 bytes each).
    • A key schedule is generated, expanding the main key into multiple round keys used throughout the encryption process.
  2. Encryption rounds:
    • Each data block goes through a series of rounds (10, 12, or 14 depending on key length). Each round consists of four basic transformations:
      • SubBytes: Substitutes each byte in the block with a different byte according to a predefined lookup table. This shuffles the data and introduces ā€œconfusion.ā€
      • ShiftRows: Shifts the rows of the byte matrix cyclically by different offsets. This disrupts any patterns in the data.
      • MixColumns: Performs a complex mixing operation on the data columns, ensuring diffusion of any remaining data patterns.
      • AddRoundKey: XORs the current block state with a round key derived from the key schedule. This incorporates the key material into each round.
  3. Finalization:
    • After all rounds, the final block becomes the encrypted ciphertext (unreadable data).

The key strength and multiple rounds make AES highly secure. Even a small change in the plain text or key will result in a completely different ciphertext, making it difficult to crack the code.

Where is AES Encryption Used in Real Life?

AES encryption plays a vital role in securing our data in various ways:

  • Secure Messaging Apps: When you use encrypted messaging apps like WhatsApp or Signal, your messages are likely protected with AES to ensure only the intended recipient can read them.
  • Encrypted Browsing: Secure websites use HTTPS, which relies on AES to encrypt communication between your browser and the server, safeguarding your data from eavesdroppers on public Wi-Fi networks.
  • Protecting Files: Popular file compression tools like WinZip or 7-Zip offer AES encryption as an option to password-protect your confidential files before storing or sharing them.
  • Securing Disks: Solid-state drives (SSDs) often have built-in hardware encryption based on AES, scrambling the data stored on the drive and requiring a password for access.
  • Financial Transactions: Banks and other financial institutions rely on AES to encrypt sensitive financial data like account numbers and transaction details, protecting them from cyberattacks.
  • Cloud Storage: Cloud storage services like Google Drive or Dropbox may use AES encryption to secure your uploaded files at rest, preventing unauthorized access even if the cloud server is compromised.

These are just a few examples, and AES encryption is the foundation of modern data security across countless applications.

How to Encrypt a Text Message Using Python

Now, letā€™s see the practical side and explore how to encrypt text using Python and the PyCryptodome library.

Requirements

To run this program, youā€™ll need Python 3 and the PyCryptodome library installed. You can install it using pip:

pip install PyCryptodome

The Program

Here is a Python program for AES-256 encryption.

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

def encrypt(data, key, filename):
  # Generate random initialization vector
  iv = get_random_bytes(AES.block_size) 
  cipher = AES.new(key, AES.MODE_CBC, iv)
  # Pad the data with PKCS#7 padding
  padded_data = pad(data, AES.block_size)  
  ciphertext = cipher.encrypt(padded_data)

  # Write the IV and ciphertext to the specified file
  with open(filename, 'wb') as f:
    f.write(iv)
    f.write(ciphertext)

if __name__ == "__main__":
  data = input("Enter the data to encrypt: ").encode()
  # Replace with your desired key (16, 24, or 32 bytes)
  key = b"Your_key_here..."  
  filename = "encrypted_data.txt"

  encrypt(data, key, filename)

  print("Encrypted data saved to", filename)

Explanation of the Program

The program will take the message (in the text form) from you and generate the encrypted data in the form of a text file (ā€œencrypted_data.txtā€). Here is the explanation of the encrypt function, the most important part of the above program:

  • def encrypt(data, key, filename): This defines a function named encrypt that takes three arguments:
    • data: The data to be encrypted (bytes).
    • key: The encryption key (bytes, length must be 16, 24, or 32).
    • filename: The name of the file to save the encrypted data.
  • iv = get_random_bytes(AES.block_size): This line generates a random initialization vector (IV) using get_random_bytes. The size of the IV is determined by the AES block size (16 bytes).
  • cipher = AES.new(key, AES.MODE_CBC, iv): This line creates a new AES cipher object using the provided key, cipher mode (CBC ā€“ Cipher Block Chaining), and the generated IV.
  • padded_data = pad(data, AES.block_size): This line pads the data with PKCS#7 padding using the pad function. Padding ensures the data length is a multiple of the block size for proper AES operation.
  • ciphertext = cipher.encrypt(padded_data): This line encrypts the padded data using the AES cipher object.
  • with open(filename, ā€˜wbā€™) as f: This line opens the file specified by ā€˜filenameā€™ in write binary mode (ā€˜wbā€™). The with statement ensures proper closing of the file even in case of errors.
  • f.write(iv): This line writes the generated IV to the opened file. The IV is essential for decryption and should be stored along with the encrypted data.
  • f.write(ciphertext): This line writes the encrypted data (ciphertext) to the opened file.

Output

Enter the data to encrypt: Agent X, Proceed with Operation Firestorm. Target location secured. Await further instructions at rendezvous point Alpha-7. Maintain utmost discretion. Code name ā€œPhoenixā€ in effect. This message will self-destruct upon reading. Stay sharp.

Encrypted data saved to encrypted_data.txt

Decrypting the Encrypted Text

Now that you have the encrypted text, youā€™ll need the same key and the encrypted text file to decrypt it and retrieve the original message. Hereā€™s the Python program for decryption:

from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad

def decrypt(data, key, filename):
  # Read the IV and ciphertext from the specified file
  with open(filename, 'rb') as f:
    # Read the first block size bytes as IV
    iv = f.read(AES.block_size)  
    ciphertext = f.read()

  cipher = AES.new(key, AES.MODE_CBC, iv)
  decrypted = cipher.decrypt(ciphertext)
  return unpad(decrypted, AES.block_size)

if __name__ == "__main__":
  # Replace with the same key used for encryption (16, 24, or 32 bytes)
  key = b"Your_key_here..."  
  filename = "encrypted_data.txt"

  # Read the combined IV and encrypted data from the file
  with open(filename, 'rb') as f:
    data = f.read()

  decrypted_data = decrypt(data, key, filename)

  print("Decrypted data:", decrypted_data.decode())

Explanation of the Program

  • def decrypt(data, key, filename): This defines a function named decrypt that takes three arguments:
    • data: The combined IV and encrypted data (ciphertext) read from the file (bytes).
    • key: The decryption key (bytes, same key used for encryption).
    • filename: The name of the file containing the encrypted data (for reference).
  • with open(filename, ā€˜rbā€™) as f: This line opens the file specified by ā€˜filenameā€™ in read binary mode (ā€˜rbā€™). The with statement ensures proper closing of the file even in case of errors.
  • iv = f.read(AES.block_size): This line reads the first AES.block_size bytes from the opened file and assigns them to the iv variable. This assumes the IV was written at the beginning of the file during encryption.
  • ciphertext = f.read(): This line reads the remaining bytes from the opened file and assigns them to the ciphertext variable. This assumes the ciphertext follows the IV in the file.
  • cipher = AES.new(key, AES.MODE_CBC, iv): This line creates a new AES cipher object using the provided key, cipher mode (CBC ā€“ Cipher Block Chaining), and the IV read from the file.
  • decrypted = cipher.decrypt(ciphertext): This line decrypts the ciphertext using the AES cipher object.
  • return unpad(decrypted, AES.block_size): This line removes PKCS#7 padding from the decrypted data using the unpad function and returns the unpadded data.

Output

Decrypted data: Agent X, Proceed with Operation Firestorm. Target location secured. Await further instructions at rendezvous point Alpha-7. Maintain utmost discretion. Code name ā€œPhoenixā€ in effect. This message will self-destruct upon reading. Stay sharp.

Generate 256-bit random keys

You can use the following program if you struggle to generate a 256-bit (32 bytes) key for the encryption program. This Python program is designed to generate a 256-bit, random key every time.

import string
import random

# length should be 16, 24, or 32
length = 32
char_pool = string.ascii_uppercase + string.ascii_lowercase + string.digits
random_text = ''.join(random.sample(char_pool, length))

print(f"Generated Key: {random_text}")

Output

Generated Key: OcIuSk8dGjHEzNYtmo4pqZDQBFsP3rlU

Conclusion

In this article, we explored an overview of the AES algorithm and implemented AES-256 encryption using Python programming. We learned how to encrypt and decrypt a text message using Pythonā€™s PyCryptodome library.

Not only text messages, you can encrypt your images also using AES encryption. Learn how to from here: How to Encrypt an Image in Python using AES Algorithm.

Remember, strong encryption relies on a secure key. Never share your encryption key!

Happy Coding!

Share your love
Subhankar Rakshit
Subhankar Rakshit

Hey there! Iā€™m Subhankar Rakshit, the brains behind PySeek. Iā€™m a Post Graduate in Computer Science. PySeek is where I channel my love for Python programming and share it with the world through engaging and informative blogs.

Articles:Ā 194