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
pip install pycryptodomeBasic 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 WorldHash: a591a6d40bf420404a011733cfb7b190d62c65bf0bcda32b57b277d9ad9f146MD5 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 AESfrom Crypto.Random import get_random_bytesimport base64
# Generate key (must be 16, 24, or 32 bytes)key = get_random_bytes(16)
# Data to encryptplaintext = "Secret Message"pad_len = 16 - (len(plaintext) % 16)plaintext = plaintext + ' ' * pad_len
# Create ciphercipher = AES.new(key, AES.MODE_ECB)
# Encryptciphertext = cipher.encrypt(plaintext.encode())encrypted = base64.b64encode(ciphertext).decode()
print(f"Plaintext: {plaintext}")print(f"Encrypted: {encrypted}")AES Decryption
from Crypto.Cipher import AESimport base64
# Key and encrypted datakey = b'sixteen byte key' # Must match encryption keyencrypted = "base64_encoded_data_here"
# Decode and decryptciphertext = 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_bytesimport string
# Generate random bytesrandom_bytes = get_random_bytes(20)
# Convert to alphanumericchars = string.ascii_letters + string.digitspassword = ''.join([random_bytes[i % len(random_bytes)] for i in range(16)])
print("Random Password:", password)
# Better wayimport secretsprint("Secure Password:", secrets.token_hex(16))Real-World Cybersecurity Uses
1. Password Hashing for Authentication
from Crypto.Hash import SHA256from 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 databasesalt, hashed = hash_password("user123")print(f"Salt: {salt.hex()}")print(f"Hash: {hashed}")
# Verify passworddef verify_password(password, salt, stored_hash): _, computed_hash = hash_password(password, salt) return computed_hash == stored_hash
# Testprint("Valid:", verify_password("user123", salt, hashed)) # Trueprint("Invalid:", verify_password("wrong", salt, hashed)) # False2. Decrypt Captured Network Traffic
from Crypto.Cipher import AESimport base64
# Simulate captured encrypted trafficcaptured_key = b'sixteen byte key'captured_data = "U2FsdGVkX1+jE4BzZ..."
# Decrypttry: 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_bytesimport base64
# Generate API tokentoken = base64.urlsafe_b64encode(get_random_bytes(32)).decode()print("API Token:", token)
# Generate session IDsession_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 hasheshashes = { "21232f297a57a5a743894a0e4a801fc3": "admin", "5f4dcc3b5aa765d61d8327deb882cf99": "password", "e10adc3949ba59abbe56e057f20f883e": "123456"}
# Check if hash is in rainbow tabledef check_md5(hash_value): if hash_value in hashes: return hashes[hash_value] return "Not found"
# Testprint(check_md5("5f4dcc3b5aa765d61d8327deb882cf99")) # passwordprint(check_md5("unknown_hash")) # Not found
# Why MD5 is weak: fast to compute, collisions possibleprint("\n⚠️ MD5 is deprecated! Use SHA256 or better.")5. RSA Encryption (Public Key)
from Crypto.PublicKey import RSAfrom Crypto.Cipher import PKCS1_OAEP
# Generate key pairkey = RSA.generate(2048)private_key = key.export_key()public_key = key.publickey().export_key()
print("Key pair generated!")
# Encrypt with public keycipher_rsa = PKCS1_OAEP.new(key.publickey())ciphertext = cipher_rsa.encrypt(b"Sensitive Data")print("Encrypted:", ciphertext.hex())
# Decrypt with private keydecipher_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
| Algorithm | Use Case |
|---|---|
SHA256 | Secure hashing |
MD5 | Weak hashing (avoid) |
AES | Symmetric encryption |
RSA | Asymmetric encryption |
get_random_bytes() | Secure random data |
Quick Reference
# Hashingfrom Crypto.Hash import SHA256h = SHA256.new(data.encode())h.hexdigest()
# AES Encryptionfrom Crypto.Cipher import AEScipher = AES.new(key, AES.MODE_ECB)cipher.encrypt(data)
# Random datafrom Crypto.Random import get_random_bytesget_random_bytes(16)
# RSA Encryptionfrom Crypto.PublicKey import RSAkey = 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!