Securely Storing User Credentials in Python: Best Practices and Examples
Safeguarding Sensitive Information
Introduction:
In many applications, it's necessary to store user credentials such as usernames and passwords securely. In this blog post, we'll discuss several methods for securely storing user credentials in Python, along with examples for each method.
Environment Variables:
Use the
os
module to set and access environment variables.Example:
import os # Set environment variables os.environ['MY_USERNAME'] = 'my_username' os.environ['MY_PASSWORD'] = 'my_password' # Access environment variables username = os.getenv('MY_USERNAME') password = os.getenv('MY_PASSWORD') print(f"Username: {username}, Password: {password}")
Configuration File:
Store credentials in a configuration file (e.g., JSON, YAML).
Assuming you have a
config.json
file:
{ "username": "my_username", "password": "my_password" }
Example using JSON:
import json with open('config.json') as f: config = json.load(f) username = config['username'] password = config['password'] print(f"Username: {username}, Password: {password}")
Secrets Management Services:
Use services like AWS Secrets Manager or Azure Key Vault.
Example using AWS Secrets Manager (requires AWS SDK for Python,
boto3
):
import boto3 # Create a Secrets Manager client client = boto3.client('secretsmanager') # Retrieve secret response = client.get_secret_value(SecretId='my_secret_id') secret = json.loads(response['SecretString']) username = secret['username'] password = secret['password'] print(f"Username: {username}, Password: {password}")
Encrypted Database:
Store credentials in an encrypted database (e.g., SQLite with encryption).
Example using SQLite with encryption (requires
pysqlcipher3
):import sqlite3 # Connect to SQLite database conn = sqlite3.connect('encrypted.db') conn.execute("ATTACH DATABASE 'encrypted.db' AS encrypted KEY 'encryption_key';") conn.execute("CREATE TABLE IF NOT EXISTS encrypted.credentials (username TEXT, password TEXT);") # Insert encrypted credentials conn.execute("INSERT INTO encrypted.credentials (username, password) VALUES ('my_username', 'my_password');") # Retrieve and decrypt credentials cursor = conn.execute("SELECT username, password FROM encrypted.credentials;") for row in cursor: username, password = row print(f"Username: {username}, Password: {password}") # Close connection conn.close()
Encrypted File:
Encrypt credentials and store them in a file.
Example using cryptography library: (requires
cryptography
)
from cryptography.fernet import Fernet # Generate encryption key key = Fernet.generate_key() cipher = Fernet(key) # Encrypt username and password encrypted_username = cipher.encrypt(b'my_username') encrypted_password = cipher.encrypt(b'my_password') # Store encrypted username and password in a file with open('credentials.enc', 'wb') as f: f.write(encrypted_username) f.write(encrypted_password) # Decrypt username and password from the file with open('credentials.enc', 'rb') as f: encrypted_username = f.readline() encrypted_password = f.readline() decrypted_username = cipher.decrypt(encrypted_username).decode() decrypted_password = cipher.decrypt(encrypted_password).decode() print(f"Username: {decrypted_username}, Password: {decrypted_password}")
Conclusion: Securely storing user credentials is crucial for protecting sensitive information in your applications. By following best practices and using the right tools, you can ensure that user credentials are stored securely and remain protected from unauthorized access.