Message Encryption and Decryption in Python

Encrypt and decrypt messages with a passphrase in Python


March 24, 2023

First, install the pycryptodome package.

pip install pycryptodome

The Code

import hashlib
from Crypto.Cipher import AES


def pad(data: bytes) -> bytes:
    length = AES.block_size - (len(data) % AES.block_size)
    return data + (chr(length) * length).encode()


def unpad(data: bytes) -> bytes:
    length = data[-1]
    return data[:-length]


def bin_to_base16(bin_data: bytes) -> str:
    return bin_data.hex()


def base16_to_bin(base16_data: str) -> bytes:
    return bytes.fromhex(base16_data)


def encrypt(message: str, password: str) -> str:
    message_bytes = pad(message.encode("utf-8"))
    password_bytes = hashlib.sha256(password.encode("utf-8")).digest()

    cipher = AES.new(password_bytes, AES.MODE_ECB)
    return bin_to_base16(cipher.encrypt(message_bytes))


def decrypt(encrypted_message: str, password: str) -> str:
    password_bytes = hashlib.sha256(password.encode("utf-8")).digest()

    cipher = AES.new(password_bytes, AES.MODE_ECB)
    message = cipher.decrypt(base16_to_bin(encrypted_message))

    return unpad(message).decode("utf-8")

Encrypt a message

encrypted_message = encrypt("Hello, World!", "password")
print(encrypted_message)

The output will be 2cd9a476c50ea46f0d826e54578e0d63.

Decrypt a message

decrypted_message = decrypt("2cd9a476c50ea46f0d826e54578e0d63", "password")
print(decrypted_message)

The output will be Hello, World!.