Symmetric Encryption in Python

Ivar Thorson bio photo By Ivar Thorson

Hashing strings is useful for creating unique identifiers for strings, blobs of data, etc. In Python, it’s sometimes handy to make your own hashing function from AES. Here’s a brief snippet of how to do that for short messages. Kind of fun!

from Crypto.Cipher import AES
import binascii


def encrypt_string(msg_text: str, secret_key: str) -> str:
    """Symmetrically encrypt a msg_text, and return as a hex string."""
    cipher = AES.new(secret_key.rjust(16), AES.MODE_ECB)
    encoded_buf = binascii.hexlify(cipher.encrypt(msg_text.rjust(16)))
    enc_str = encoded_buf.decode()  # 'decode' is for binary to UTF-8
    return enc_str


def decrypt_string(hex_encoded_msg: str,  secret_key: str) -> str:
    """Symmetrically decrypt hexencoded_msg, and return the resulting string."""
    cipher = AES.new(secret_key.rjust(16), AES.MODE_ECB)
    decoded_buf = cipher.decrypt(binascii.unhexlify(hex_encoded_msg))
    dec_str = decoded_buf.strip().decode()
    return dec_str

If you are trying to encrypt and decrypt general files, GPG is of course a much better choice.