Information Security 11 min read

Python Encryption and Decryption Code Examples for Various Algorithms

This article provides Python implementations and usage examples for a range of encryption and decryption techniques—including AES, RSA, Caesar cipher, Base64, SHA‑256/HMAC, Blowfish, DES, ChaCha20‑Poly1305, and XOR—along with notes on required libraries and security considerations.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Python Encryption and Decryption Code Examples for Various Algorithms

This guide demonstrates how to encrypt and decrypt data in Python using multiple cryptographic algorithms. Each section includes the necessary imports, function definitions, and a short usage example. Some algorithms require external libraries such as pycryptodome or cryptography .

AES (Advanced Encryption Standard)

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

def encrypt_AES(message, key):
    cipher = AES.new(key, AES.MODE_CBC)
    ct_bytes = cipher.encrypt(pad(message.encode(), AES.block_size))
    return (cipher.iv + ct_bytes).hex()

def decrypt_AES(ciphertext, key):
    ciphertext_bytes = bytes.fromhex(ciphertext)
    iv, ct_bytes = ciphertext_bytes[:AES.block_size], ciphertext_bytes[AES.block_size:]
    cipher = AES.new(key, AES.MODE_CBC, iv)
    plaintext = unpad(cipher.decrypt(ct_bytes), AES.block_size)
    return plaintext.decode()

# Example usage
key = get_random_bytes(16)
message = "Hello, World!"
ciphertext = encrypt_AES(message, key)
print("Ciphertext:", ciphertext)
plaintext = decrypt_AES(ciphertext, key)
print("Plaintext:", plaintext)

RSA (Asymmetric Encryption)

from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP

def generate_RSA_keys():
    key = RSA.generate(2048)
    public_key = key.publickey().export_key()
    private_key = key.export_key()
    return public_key, private_key

def encrypt_RSA(message, public_key):
    public_key = RSA.import_key(public_key)
    cipher = PKCS1_OAEP.new(public_key)
    ct_bytes = cipher.encrypt(message.encode())
    return ct_bytes.hex()

def decrypt_RSA(ciphertext, private_key):
    private_key = RSA.import_key(private_key)
    cipher = PKCS1_OAEP.new(private_key)
    ct_bytes = bytes.fromhex(ciphertext)
    plaintext = cipher.decrypt(ct_bytes).decode()
    return plaintext

# Example usage
public_key, private_key = generate_RSA_keys()
message = "Hello, World!"
ciphertext = encrypt_RSA(message, public_key)
print("Ciphertext:", ciphertext)
plaintext = decrypt_RSA(ciphertext, private_key)
print("Plaintext:", plaintext)

Caesar Cipher (Simple Shift Cipher)

def caesar_cipher_encrypt(text, shift):
    encrypted_text = ""
    for char in text:
        if char.isalpha():
            shifted_char = chr(((ord(char.lower()) - ord('a') + shift) % 26) + ord('a'))
            if char.isupper():
                encrypted_text += shifted_char.upper()
            else:
                encrypted_text += shifted_char
        else:
            encrypted_text += char
    return encrypted_text

def caesar_cipher_decrypt(encrypted_text, shift):
    return caesar_cipher_encrypt(encrypted_text, -shift)

# Example usage
text = "Hello, World!"
shift = 3
encrypted_text = caesar_cipher_encrypt(text, shift)
print("Encrypted Text:", encrypted_text)
decrypted_text = caesar_cipher_decrypt(encrypted_text, shift)
print("Decrypted Text:", decrypted_text)

Base64 Encoding (Not Encryption)

import base64

def base64_encode(text):
    return base64.b64encode(text.encode()).decode()

def base64_decode(encoded_text):
    return base64.b64decode(encoded_text).decode()

# Example usage
text = "Hello, World!"
encoded_text = base64_encode(text)
print("Encoded Text:", encoded_text)
decoded_text = base64_decode(encoded_text)
print("Decoded Text:", decoded_text)

SHA‑256 Hashing and HMAC

import hashlib

def hash_SHA256(text):
    sha256_hash = hashlib.sha256()
    sha256_hash.update(text.encode())
    return sha256_hash.hexdigest()

import hmac
import hashlib

def HMAC_SHA256(message, key):
    hmac_instance = hmac.new(key.encode(), message.encode(), hashlib.sha256)
    return hmac_instance.hexdigest()

# Example usage
text = "Hello, World!"
hashed_text = hash_SHA256(text)
print("Hashed Text:", hashed_text)
message = "Hello, World!"
key = "my_secret_key"
hmac_signature = HMAC_SHA256(message, key)
print("HMAC Signature:", hmac_signature)

Blowfish Encryption

from Crypto.Cipher import Blowfish
from Crypto.Util.Padding import pad, unpad

def encrypt_Blowfish(message, key):
    cipher = Blowfish.new(key, Blowfish.MODE_CBC)
    ct_bytes = cipher.encrypt(pad(message.encode(), Blowfish.block_size))
    return (cipher.iv + ct_bytes).hex()

def decrypt_Blowfish(ciphertext, key):
    ciphertext_bytes = bytes.fromhex(ciphertext)
    iv, ct_bytes = ciphertext_bytes[:Blowfish.block_size], ciphertext_bytes[Blowfish.block_size:]
    cipher = Blowfish.new(key, Blowfish.MODE_CBC, iv)
    plaintext = unpad(cipher.decrypt(ct_bytes), Blowfish.block_size)
    return plaintext.decode()

# Example usage
key = b"my_secret_key" * 8
message = "Hello, World!"
ciphertext = encrypt_Blowfish(message, key)
print("Ciphertext:", ciphertext)
plaintext = decrypt_Blowfish(ciphertext, key)
print("Plaintext:", plaintext)

DES Encryption

from Crypto.Cipher import DES
from Crypto.Util.Padding import pad, unpad

def encrypt_DES(message, key):
    cipher = DES.new(key, DES.MODE_CBC)
    ct_bytes = cipher.encrypt(pad(message.encode(), DES.block_size))
    return (cipher.iv + ct_bytes).hex()

def decrypt_DES(ciphertext, key):
    ciphertext_bytes = bytes.fromhex(ciphertext)
    iv, ct_bytes = ciphertext_bytes[:DES.block_size], ciphertext_bytes[DES.block_size:]
    cipher = DES.new(key, DES.MODE_CBC, iv)
    plaintext = unpad(cipher.decrypt(ct_bytes), DES.block_size)
    return plaintext.decode()

# Example usage
key = b"my_secret_key"[:8]
message = "Hello, World!"
ciphertext = encrypt_DES(message, key)
print("Ciphertext:", ciphertext)
plaintext = decrypt_DES(ciphertext, key)
print("Plaintext:", plaintext)

ChaCha20‑Poly1305 Authenticated Encryption

from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305
from cryptography.hazmat.backends import default_backend

def encrypt_ChaCha20Poly1305(message, key, nonce):
    cipher = Cipher(algorithms.Chacha20Poly1305(key), modes.NULL, backend=default_backend())
    encryptor = cipher.encryptor()
    encryptor.authenticate_additional_data(nonce)
    ct = encryptor.update(message.encode()) + encryptor.finalize()
    tag = encryptor.tag
    return ct.hex() + tag.hex()

def decrypt_ChaCha20Poly1305(ciphertext, key, nonce):
    ct_bytes = bytes.fromhex(ciphertext[:-32])
    tag_bytes = bytes.fromhex(ciphertext[-32:])
    cipher = Cipher(algorithms.Chacha20Poly1305(key), modes.NULL, backend=default_backend())
    decryptor = cipher.decryptor()
    decryptor.authenticate_additional_data(nonce)
    decryptor.authenticate(tag_bytes)
    plaintext = decryptor.update(ct_bytes) + decryptor.finalize()
    return plaintext.decode()

# Example usage
key = get_random_bytes(32)
nonce = get_random_bytes(12)
message = "Hello, World!"
ciphertext = encrypt_ChaCha20Poly1305(message, key, nonce)
print("Ciphertext:", ciphertext)
plaintext = decrypt_ChaCha20Poly1305(ciphertext, key, nonce)
print("Plaintext:", plaintext)

XOR Cipher (Simple, Insecure Example)

def xor_cipher_encrypt(message, key):
    encrypted_text = bytearray()
    for i in range(len(message)):
        encrypted_text.append(message[i] ^ key[i % len(key)])
    return bytes(encrypted_text).hex()

def xor_cipher_decrypt(encrypted_text, key):
    return xor_cipher_encrypt(encrypted_text, key)

# Example usage
message = "Hello, World!"
key = b"my_secret_key"
encrypted_text = xor_cipher_encrypt(message.encode(), key)
print("Encrypted Text:", encrypted_text)
decrypted_text = xor_cipher_decrypt(encrypted_text, key)
print("Decrypted Text:", decrypted_text)

Note: Some of these examples require installing additional packages (e.g., pycryptodome or cryptography ). In real applications, choose algorithms and libraries that meet your security requirements and manage keys and parameters carefully.

pythonRSAEncryptionAEScaesar-cipherdecryption
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.