Message Encryption using Python

Message Encryption means keeping the message secret. In simple words, Message Encryption means putting the message in a secret box that only the receiver can open. If you want to learn how to encrypt messages using Python, this article is for you. In this article, I will take you through the task of message encryption using Python.

Message Encryption

Before implementing Message Encryption using Python, let’s look at the process of Message Encryption. Here’s the complete process of Message Encryption that messaging apps follow:

  1. First, choose a secret key that to encrypt the message. This key is a password only the person supposed to read the message knows.
  2. Then take the message and scramble it using the key. It means turning the message into a secret code like a jumble of letters or numbers.
  3. Once the message is scrambled, it is delivered to the person who is supposed to read it. But if anyone else tries to read it, they’ll see a jumble of letters or numbers that don’t make sense.

So, Message Encryption is like having a secret code that only the person who is supposed to read the message can understand.

Message Encryption using Python

Now let’s get started with the task of Message Encryption using Python. For this task, you need to have a library installed in your system known as cryptography. You can easily install it by executing the command mentioned below in your terminal or command prompt:

  • pip install cryptography

Now let’s first create a conversation between two people using a Python dictionary:

message_data = {
    "Aman": [
        {"message": "Hey Divyansha, how's it going?", "time": "2023-03-21 10:30:00"},
        {"message": "Not too bad, just working on some coding projects. Did you hear about the new encryption algorithm?", "time": "2023-03-21 10:35:00"},
        {"message": "It's called AES256 and it's supposed to be really secure. Want to give it a try with our messages?", "time": "2023-03-21 10:40:00"},
    ],
    "Divyansha": [
        {"message": "Good, thanks! How about you?", "time": "2023-03-21 10:32:00"},
        {"message": "No, what's that?", "time": "2023-03-21 10:37:00"},
        {"message": "Sure, let's do it!", "time": "2023-03-21 10:42:00"},
    ]
}

Now let’s import the necessary modules and then generate a shared secret key for encryption and decryption:

import os
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
shared_secret_key = os.urandom(32)

Now let’s define a function to keep the secret message safe from people who shouldn’t see it:

def encrypt_message(message, key):
    iv = os.urandom(16)
    cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())
    encryptor = cipher.encryptor()
    padded_message = message + (16 - len(message) % 16) * chr(16 - len(message) % 16)
    ciphertext = encryptor.update(padded_message.encode()) + encryptor.finalize()
    return iv + ciphertext

Now let’s define a function to unscramble the secret message made using a key and encryption:

def decrypt_message(ciphertext, key):
    iv = ciphertext[:16]
    cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())
    decryptor = cipher.decryptor()
    plaintext = decryptor.update(ciphertext[16:]) + decryptor.finalize()
    padding_length = plaintext[-1]
    plaintext = plaintext[:-padding_length]
    return plaintext.decode()

Now here’s how we can encrypt the dictionary with the scrambled messages so that only the people who know the key can unscramble and read the messages:

for person, messages in message_data.items():
    for message in messages:
        encrypted_message = encrypt_message(message["message"], shared_secret_key)
        message["message"] = encrypted_message.hex()

print("Encrypted message_data dictionary:")
print(message_data)
Encrypted message_data dictionary:
{'Aman': [{'message': '67e03426da00a7fcc69317820619c7868bb95f6787882b9441db7f89f89367af92bd2ab7386ddb06a9c6036ed764f8b1', 'time': '2023-03-21 10:30:00'}, {'message': 'af78f1cbbbd8103c8db21e042d1c36e8167695a3aa4b2acc3ac5c788abb89260ac6b990bf8344d897a623b8fb556ba4ce04e3255381856815c651b1d93efc0e0424ee1495ab1a72e2a20948c21d51ddbec3e66a493668ad60a9840e436beceb5c34786e05a4f9f71fb5ed2a70ec838994fa545d7c03da15d9850fb5061259df7', 'time': '2023-03-21 10:35:00'}, {'message': '91a5e6eb65ba1550f00dc4b05649d43a3f6792b0c2682e72f09f690f13f0d176ddfb0a6f46abfcd9065735b4cb611e0a3d2119bf0f9b0b6f2ac4501cafc40d71e89dabcd41f5f5b2e544bcbd7556890307a2201e91f70c6e20742bc956886b98ec929eaded5c16036e1449aafb3024ca5dad5dd29b1148e9535586406f8422c7', 'time': '2023-03-21 10:40:00'}], 'Divyansha': [{'message': 'e3ba528d38fe41424434cfd610d73647628867fc059214bda2c177c85b004bb675600b101cf32b4e302264d550091642', 'time': '2023-03-21 10:32:00'}, {'message': '99f1c86dfa530d59b404cc2cf62d278a6124274a365b60397aacb0f82c1b76c596b132678df76943ae31a14a230ea7c4', 'time': '2023-03-21 10:37:00'}, {'message': '6b51e93dcf9e524e94563a5d3b9224b9e30007cbfb61056d2b6a641dee5d3df156e092380f8f8f00f87387ae75c7049c', 'time': '2023-03-21 10:42:00'}]}

Now here’s how to decrypt the encrypted messages so that the people having the key can read the messages:

for person, messages in message_data.items():
    for message in messages:
        ciphertext = bytes.fromhex(message["message"])
        decrypted_message = decrypt_message(ciphertext, shared_secret_key)
        message["message"] = decrypted_message

print("Decrypted message_data dictionary:")
print(message_data)
Decrypted message_data dictionary:
{'Aman': [{'message': "Hey Divyansha, how's it going?", 'time': '2023-03-21 10:30:00'}, {'message': 'Not too bad, just working on some coding projects. Did you hear about the new encryption algorithm?', 'time': '2023-03-21 10:35:00'}, {'message': "It's called AES256 and it's supposed to be really secure. Want to give it a try with our messages?", 'time': '2023-03-21 10:40:00'}], 'Divyansha': [{'message': 'Good, thanks! How about you?', 'time': '2023-03-21 10:32:00'}, {'message': "No, what's that?", 'time': '2023-03-21 10:37:00'}, {'message': "Sure, let's do it!", 'time': '2023-03-21 10:42:00'}]}

So this is how we can encrypt and decrypt messages using the Python programming language.

Summary

Message Encryption means putting the message in a secret box only the receiver can open. I hope you liked this article on Message Encryption using Python. You can find many more Python projects solved and explained to improve your Python programming skills from here. Feel free to ask valuable questions in the comments section below.

Aman Kharwal
Aman Kharwal

Data Strategist at Statso. My aim is to decode data science for the real world in the most simple words.

Articles: 1619

Leave a Reply

Discover more from thecleverprogrammer

Subscribe now to keep reading and get access to the full archive.

Continue reading