Python Techniques for Data Protection and Privacy: Encryption, Hashing, SSL/TLS, and Common Security Measures
This article presents practical Python examples for enhancing network security, covering symmetric and asymmetric encryption, hash functions, password hashing, SSL/TLS communication, SQL injection prevention, XSS mitigation, CSRF protection, and secure password storage to safeguard data and privacy.
Network security is crucial for protecting data and privacy. Python offers several libraries and tools to help strengthen security.
1. Encrypt and decrypt data
Use the cryptography library for symmetric encryption with Fernet, and the RSA algorithm for asymmetric encryption.
from cryptography.fernet import Fernet
# Generate encryption key
key = Fernet.generate_key()
# Create cipher
cipher = Fernet(key)
# Encrypt data
encrypted_data = cipher.encrypt(b"Hello, World!")
# Decrypt data
decrypted_data = cipher.decrypt(encrypted_data)
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import hashes
# Generate RSA key pair
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
public_key = private_key.public_key()
# Encrypt data
encrypted_data = public_key.encrypt(
b"Hello, World!",
padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None)
)
# Decrypt data
decrypted_data = private_key.decrypt(
encrypted_data,
padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None)
)2. Hash functions
Use the hashlib library to compute MD5 and SHA256 hashes.
import hashlib
# MD5 hash
md5_hash = hashlib.md5(b"Hello, World!")
md5_digest = md5_hash.hexdigest()
# SHA256 hash
sha256_hash = hashlib.sha256(b"Hello, World!")
sha256_digest = sha256_hash.hexdigest()3. Password hashing and verification
Use the passlib library.
from passlib.hash import pbkdf2_sha256
# Generate password hash
hashed_password = pbkdf2_sha256.hash("password123")
# Verify password
is_valid = pbkdf2_sha256.verify("password123", hashed_password)4. SSL/TLS communication
Use the ssl library together with socket to create a secure connection.
import ssl
import socket
# Create SSL context
context = ssl.create_default_context()
# Create secure TCP connection
with socket.create_connection(('www.example.com', 443)) as sock:
with context.wrap_socket(sock, server_hostname='www.example.com') as ssock:
ssock.send(b"Hello, World!")
response = ssock.recv(1024)5. Prevent SQL injection
Use parameterized queries or an ORM such as SQLAlchemy.
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
# Create engine
engine = create_engine('sqlite:///mydatabase.db')
Session = sessionmaker(bind=engine)
session = Session()
# Parameterized query
username = "admin' OR '1'='1"
password = "password123"
query = "SELECT * FROM users WHERE username=:username AND password=:password"
result = session.execute(query, {'username': username, 'password': password})6. Prevent cross-site scripting (XSS)
Use a template engine like Jinja2 with automatic escaping.
from jinja2 import Template
user_input = ''
template = Template("Hello, {{ user_input|e }}!")
output = template.render(user_input=user_input)7. Prevent cross-site request forgery (CSRF)
Generate and verify CSRF tokens, e.g., with Flask.
from flask import Flask, request, session
import secrets
app = Flask(__name__)
app.secret_key = secrets.token_hex(16)
@app.route('/login', methods=['POST'])
def login():
csrf_token = secrets.token_hex(16)
session['csrf_token'] = csrf_token
login_form = f'
' \
f'
' \
f'
' \
f'
' \
f'
' \
f'
'
return login_form
@app.route('/authenticate', methods=['POST'])
def authenticate():
csrf_token = request.form.get('csrf_token')
if csrf_token != session.pop('csrf_token', None):
return 'Invalid CSRF token'
# Perform authentication
return 'Authenticated'
if __name__ == '__main__':
app.run()8. Secure password storage
Store passwords using a hash function with a salt, e.g., via Passlib.
from passlib.hash import pbkdf2_sha256
password = "password123"
hashed_password = pbkdf2_sha256.hash(password)
is_valid = pbkdf2_sha256.verify(password, hashed_password)These methods and libraries provide a foundation for protecting data and privacy, but comprehensive security also requires authentication, authorization, network defenses, and adherence to best practices.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.