🔐 Cryptography in Python
Python has excellent libraries for secure communication and data protection.
🔑 Hashing with hashlib
Hashing is a one-way process to convert data into a fixed-size string. It's used for password storage and data integrity.
import hashlib
data = "Secret Message".encode('utf-8')
hash_object = hashlib.sha256(data)
hex_dig = hash_object.hexdigest()
print(hex_dig)
# e.g., 2bb80d537b1da3e38bd30361aa855686bde0eacd7162fef6a25fe97bf527a25b
Note: Always salt passwords before hashing!
🛡 HMAC (Hash-based Message Authentication Code)
Ensures both integrity and authenticity of a message using a secret key.
import hmac
import hashlib
key = b'secret_key'
message = b'Hello World'
h = hmac.new(key, message, hashlib.sha256)
print(h.hexdigest())
🎲 Secure Randomness with secrets
Don't use random for security purposes. Use secrets.
import secrets
token = secrets.token_hex(16)
print(token) # Secure random hex string
url_token = secrets.token_urlsafe(16)
print(url_token) # Secure URL-safe string
📦 The cryptography Library
For robust encryption, use the cryptography package (needs installation: pip install cryptography).
Symmetric Encryption (Fernet)
from cryptography.fernet import Fernet
# Generate a key
key = Fernet.generate_key()
cipher_suite = Fernet(key)
# Encrypt
text = b"My Secret Data"
cipher_text = cipher_suite.encrypt(text)
print(cipher_text)
# Decrypt
plain_text = cipher_suite.decrypt(cipher_text)
print(plain_text) # b"My Secret Data"
📝 Summary
- ✅ Hashing: One-way (
hashlib). - ✅ HMAC: Integrity + Authenticity.
- ✅ Secrets: Cryptographically strong random numbers.
- ✅ Fernet: Easy symmetric encryption.
Created with ❤️ by Pynfinity