You’re the Expert!

pynfinity

Build mountain with each pebble 🧗

Topics | Stepping Stones

📚 Guides

🌍 Pebbles & Contributions

✍️ Write a Post
🐼 Pandas DataFrames
🐼 Pandas DataFrames
🔢 NumPy Arrays
🔢 NumPy Arrays
📉 Matplotlib Plotting
📉 Matplotlib Plotting
🔥 Seaborn Heatmaps
🔥 Seaborn Heatmaps
🤖 Scikit-Learn Linear Regression
🤖 Scikit-Learn Linear Regression
🧹 Data Cleaning with Dropna
🧹 Data Cleaning with Dropna
🔍 Exploratory Data Analysis (EDA)
🔍 Exploratory Data Analysis (EDA)
⏳ Time Series Resampling
⏳ Time Series Resampling
🕸️ Web Scraping with BeautifulSoup
🕸️ Web Scraping with BeautifulSoup
🗄️ SQLAlchemy Basics
🗄️ SQLAlchemy Basics
📊 Interactive Plots with Plotly
📊 Interactive Plots with Plotly
📝 NLTK Tokenization
📝 NLTK Tokenization
🧠 TensorFlow Basics
🧠 TensorFlow Basics
🔥 PyTorch Tensors
🔥 PyTorch Tensors
📉 Statsmodels OLS
📉 Statsmodels OLS
📸 OpenCV Image Reading
📸 OpenCV Image Reading
🕸️ NetworkX Graphs
🕸️ NetworkX Graphs
🗺️ Folium Maps
🗺️ Folium Maps
🚀 Streamlit Apps
🚀 Streamlit Apps
⚡ FastAPI Endpoints
⚡ FastAPI Endpoints
✨ Jupyter Magic Commands
✨ Jupyter Magic Commands
📦 Virtual Environments
📦 Virtual Environments
🌲 Git Basics
🌲 Git Basics
🐳 Dockerfiles
🐳 Dockerfiles
☁️ AWS S3 with Boto3
☁️ AWS S3 with Boto3
🧩 Regular Expressions
🧩 Regular Expressions
λ Lambda Functions
λ Lambda Functions
📜 List Comprehensions
📜 List Comprehensions
⚡ Generators
⚡ Generators
🎀 Decorators
🎀 Decorators
🚪 Context Managers
🚪 Context Managers
🧵 Multithreading
🧵 Multithreading
🎛️ Multiprocessing
🎛️ Multiprocessing
⏳ AsyncIO
⏳ AsyncIO
🏷️ Type Hinting
🏷️ Type Hinting
📦 Dataclasses
📦 Dataclasses
🛡️ Pydantic Models
🛡️ Pydantic Models
🧪 Pytest Testing
🧪 Pytest Testing
🪵 Logging
🪵 Logging
💻 Argparse CLI
💻 Argparse CLI
📄 JSON Handling
📄 JSON Handling
📊 CSV Processing
📊 CSV Processing
🥒 Pickle Serialization
🥒 Pickle Serialization
🖥️ OS Module
🖥️ OS Module
⚙️ Sys Module
⚙️ Sys Module
📚 Collections Module
📚 Collections Module
🔁 Itertools
🔁 Itertools
🛠️ Functools
🛠️ Functools
➗ Math Module
➗ Math Module
+ New Post

🔐 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