Generate Encryption Keys in Python - Cryptography Library Examples
Complete code tutorial with examples and best practices
[ Code Example - Quick Summary ]
Language: Python
What: Generate AES and RSA encryption keys in Python using the cryptography library for secure encryption and decryption.
Try it: Use our interactive Encryption-keys generator or integrate this code into your Python application.
Generate AES and RSA encryption keys in Python using the cryptography library for secure encryption and decryption. Looking for other languages? Check our code examples in PHP , JavaScript , Java , C# , C++ , Ruby and Go or use our interactive web generator.
Python Code Example
# Install: pip install cryptography
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization
from cryptography.fernet import Fernet
import secrets
# AES-256 Key Generation (Fernet uses AES-128-CBC)
fernet_key = Fernet.generate_key()
print(f"Fernet Key (Base64): {fernet_key.decode()}")
# Raw AES-256 Key (32 bytes)
aes_256_key = secrets.token_bytes(32)
aes_256_hex = aes_256_key.hex()
print(f"AES-256 Key (Hex): {aes_256_hex}")
# AES-128 Key (16 bytes)
aes_128_key = secrets.token_hex(16) # Returns hex string
print(f"AES-128 Key (Hex): {aes_128_key}")
# RSA Key Pair Generation (2048-bit)
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048
)
# Export private key
private_pem = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption()
)
# Export public key
public_key = private_key.public_key()
public_pem = public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
)
print(f"Private Key:\n{private_pem.decode()}")
print(f"Public Key:\n{public_pem.decode()}")
[EXPLANATION]
Python's cryptography library provides robust encryption key generation. Fernet.generate_key() creates a URL-safe base64-encoded 32-byte key for Fernet symmetric encryption (uses AES-128-CBC internally with HMAC authentication). For raw AES keys, use secrets.token_bytes() (32 bytes for AES-256, 16 for AES-128) or secrets.token_hex() for hexadecimal output. rsa.generate_private_key() creates RSA key pairs with customizable key size (2048 or 4096 bits). The serialization module exports keys in PEM format. Use NoEncryption() for unencrypted private keys or BestAvailableEncryption(password) to password-protect private keys.
Expected Output
Fernet Key (Base64): xJ3K8vN2L5pR9tY7qW4eA6fD8hG1jM3nP5sT7uV9xZ= AES-256 Key (Hex): c7e2f5a9d3b8e1c4f7a2d6b9e3c5f8a1d4b7e9c2f5a8d1b4e7f9c3a6d8e2f5a9 AES-128 Key (Hex): f3a7d2e5c1b8f4a9d6c3e7b2f5a8c1d4 Private Key: -----BEGIN PRIVATE KEY----- MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC5... -----END PRIVATE KEY----- Public Key: -----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAub... -----END PUBLIC KEY-----
Common Use Cases
- Encrypt sensitive data at rest (databases, files)
- Secure API communication with encrypted payloads
- Digital signature creation and verification
- Password manager encryption
- Encrypt environment variables
Important Notes
-
Install:
pip install cryptography -
Use
secretsmodule (Python 3.6+) for cryptographic randomness - Fernet provides authenticated encryption (AES-128-CBC + HMAC-SHA256)
- RSA public exponent 65537 is standard for security and performance
-
For password-protected keys:
BestAvailableEncryption(b"password")
Try Our Interactive Generator
Don't want to write code? Use our free web-based Encryption-keys generator with instant results.
TRY ENCRYPTION-KEYS GENERATOR →Other Programming Languages
View Encryption-keys generation code examples in PHP
View Encryption-keys generation code examples in JavaScript
View Encryption-keys generation code examples in Java
View Encryption-keys generation code examples in C#
View Encryption-keys generation code examples in C++
View Encryption-keys generation code examples in Ruby
View Encryption-keys generation code examples in Go