631 words
3 minutes
Python pycryptodome Module - Complete Tutorial

🔐 pycryptodome Module#

What is pycryptodome?#

pycryptodome is a powerful Python cryptography library. It provides tools for encryption, decryption, hashing, and analyzing cryptographic algorithms.


Why Use It in Cybersecurity?#

  • Encrypt and decrypt data
  • Hash passwords and data
  • Generate secure passwords
  • Decrypt captured data
  • Analyze weak encryption
  • Test cryptography implementations
  • Create secure communication tools

Installation#

Terminal window
pip install pycryptodome

Basic Usage#

Hashing with SHA256#

from Crypto.Hash import SHA256
data = "Hello World"
hash_obj = SHA256.new(data.encode())
hash_hex = hash_obj.hexdigest()
print(f"Data: {data}")
print(f"Hash: {hash_hex}")

Output:

Data: Hello World
Hash: a591a6d40bf420404a011733cfb7b190d62c65bf0bcda32b57b277d9ad9f146

MD5 Hash#

from Crypto.Hash import MD5
password = "admin123"
hash_obj = MD5.new(password.encode())
md5_hash = hash_obj.hexdigest()
print(f"Password: {password}")
print(f"MD5: {md5_hash}")

AES Encryption#

from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
import base64
# Generate key (must be 16, 24, or 32 bytes)
key = get_random_bytes(16)
# Data to encrypt
plaintext = "Secret Message"
pad_len = 16 - (len(plaintext) % 16)
plaintext = plaintext + ' ' * pad_len
# Create cipher
cipher = AES.new(key, AES.MODE_ECB)
# Encrypt
ciphertext = cipher.encrypt(plaintext.encode())
encrypted = base64.b64encode(ciphertext).decode()
print(f"Plaintext: {plaintext}")
print(f"Encrypted: {encrypted}")

AES Decryption#

from Crypto.Cipher import AES
import base64
# Key and encrypted data
key = b'sixteen byte key' # Must match encryption key
encrypted = "base64_encoded_data_here"
# Decode and decrypt
ciphertext = base64.b64decode(encrypted)
cipher = AES.new(key, AES.MODE_ECB)
plaintext = cipher.decrypt(ciphertext).decode()
print(f"Decrypted: {plaintext.strip()}")

Generate Random Password#

from Crypto.Random import get_random_bytes
import string
# Generate random bytes
random_bytes = get_random_bytes(20)
# Convert to alphanumeric
chars = string.ascii_letters + string.digits
password = ''.join([random_bytes[i % len(random_bytes)] for i in range(16)])
print("Random Password:", password)
# Better way
import secrets
print("Secure Password:", secrets.token_hex(16))

Real-World Cybersecurity Uses#

1. Password Hashing for Authentication#

from Crypto.Hash import SHA256
from Crypto.Random import get_random_bytes
def hash_password(password, salt=None):
if salt is None:
salt = get_random_bytes(16)
# Combine password + salt
data = password.encode() + salt
# Hash
hash_obj = SHA256.new(data)
return salt, hash_obj.hexdigest()
# Store these in database
salt, hashed = hash_password("user123")
print(f"Salt: {salt.hex()}")
print(f"Hash: {hashed}")
# Verify password
def verify_password(password, salt, stored_hash):
_, computed_hash = hash_password(password, salt)
return computed_hash == stored_hash
# Test
print("Valid:", verify_password("user123", salt, hashed)) # True
print("Invalid:", verify_password("wrong", salt, hashed)) # False

2. Decrypt Captured Network Traffic#

from Crypto.Cipher import AES
import base64
# Simulate captured encrypted traffic
captured_key = b'sixteen byte key'
captured_data = "U2FsdGVkX1+jE4BzZ..."
# Decrypt
try:
decoded = base64.b64decode(captured_data)
cipher = AES.new(captured_key, AES.MODE_CBC, iv=b'sixteen byte iv')
decrypted = cipher.decrypt(decoded).decode()
print("Decrypted Traffic:", decrypted)
except Exception as e:
print("Decryption failed:", e)

3. Generate Secure Tokens#

from Crypto.Random import get_random_bytes
import base64
# Generate API token
token = base64.urlsafe_b64encode(get_random_bytes(32)).decode()
print("API Token:", token)
# Generate session ID
session_id = base64.urlsafe_b64encode(get_random_bytes(24)).decode()
print("Session ID:", session_id)

4. Check MD5 Weakness (Rainbow Tables)#

from Crypto.Hash import MD5
# Common password MD5 hashes
hashes = {
"21232f297a57a5a743894a0e4a801fc3": "admin",
"5f4dcc3b5aa765d61d8327deb882cf99": "password",
"e10adc3949ba59abbe56e057f20f883e": "123456"
}
# Check if hash is in rainbow table
def check_md5(hash_value):
if hash_value in hashes:
return hashes[hash_value]
return "Not found"
# Test
print(check_md5("5f4dcc3b5aa765d61d8327deb882cf99")) # password
print(check_md5("unknown_hash")) # Not found
# Why MD5 is weak: fast to compute, collisions possible
print("\n⚠️ MD5 is deprecated! Use SHA256 or better.")

5. RSA Encryption (Public Key)#

from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
# Generate key pair
key = RSA.generate(2048)
private_key = key.export_key()
public_key = key.publickey().export_key()
print("Key pair generated!")
# Encrypt with public key
cipher_rsa = PKCS1_OAEP.new(key.publickey())
ciphertext = cipher_rsa.encrypt(b"Sensitive Data")
print("Encrypted:", ciphertext.hex())
# Decrypt with private key
decipher_rsa = PKCS1_OAEP.new(key)
decrypted = decipher_rsa.decrypt(ciphertext)
print("Decrypted:", decrypted.decode())

⚠️ Ethical Note#

  • Never hardcode encryption keys in code
  • Use strong algorithms (avoid MD5, RC4)
  • Always use unique salts for password hashing
  • Don’t roll your own crypto - use proven libraries

![Image: Encryption/decryption diagram placeholder]


Summary Table#

AlgorithmUse Case
SHA256Secure hashing
MD5Weak hashing (avoid)
AESSymmetric encryption
RSAAsymmetric encryption
get_random_bytes()Secure random data

Quick Reference#

# Hashing
from Crypto.Hash import SHA256
h = SHA256.new(data.encode())
h.hexdigest()
# AES Encryption
from Crypto.Cipher import AES
cipher = AES.new(key, AES.MODE_ECB)
cipher.encrypt(data)
# Random data
from Crypto.Random import get_random_bytes
get_random_bytes(16)
# RSA Encryption
from Crypto.PublicKey import RSA
key = RSA.generate(2048)

Tip: When choosing encryption:

  • AES for symmetric encryption (same key to encrypt/decrypt)
  • RSA for asymmetric encryption (public/private key pair)
  • SHA256 for hashing (one-way, can’t reverse)

Warning: Cryptography is complex. Test thoroughly before using in production!