Generate Strong SSH Keys and Save Them Securely with Python
Generate a 4096-bit RSA SSH key pair using Python's cryptography library and save both private and public keys with restricted file permissions.
pip install cryptography
Python code
40 linesimport os
import stat
from pathlib import Path
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.backends import default_backend
def generate_ssh_keypair(key_path: str = "id_rsa", passphrase: str = None):
"""Generate a 4096-bit SSH key pair and save securely."""
key = rsa.generate_private_key(
public_exponent=65537,
key_size=4096,
backend=default_backend()
)
private_key_path = Path(key_path)
public_key_path = private_key_path.with_suffix(".pub")
# Save private key with restricted permissions (owner read/write only)
encryption = serialization.BestAvailableEncryption(passphrase.encode()) if passphrase else serialization.NoEncryption()
private_bytes = key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.OpenSSH,
encryption_algorithm=encryption
)
private_key_path.write_bytes(private_bytes)
private_key_path.chmod(stat.S_IRUSR | stat.S_IWUSR) # 0o600
# Save public key
public_bytes = key.public_key().public_bytes(
encoding=serialization.Encoding.OpenSSH,
format=serialization.PublicFormat.OpenSSH
)
public_key_path.write_bytes(public_bytes)
public_key_path.chmod(stat.S_IRUSR | stat.S_IWUSR)
print(f"SSH key pair saved: {private_key_path} and {public_key_path}")
if __name__ == "__main__":
generate_ssh_keypair(passphrase="my_secure_passphrase")
Output
SSH key pair saved: id_rsa and id_rsa.pub
How it works
This code uses the cryptography library to generate a strong 4096-bit RSA key with a secure public exponent (65537). The private key is serialized in OpenSSH format and optionally encrypted with a passphrase for added security. Both key files are saved with 0o600 permissions (owner read/write only) using chmod, preventing unauthorized access on multi-user systems.
Common mistakes
- Using a weak key size (e.g., 1024 bits) instead of 2048 or 4096
- Forgetting to set restrictive file permissions on the private key
- Hardcoding the passphrase in production code rather than using environment variables or prompts
Variations
- Use `ec` (Elliptic Curve) instead of `rsa` by importing `cryptography.hazmat.primitives.asymmetric.ec`
- Load an existing private key from memory using `serialization.load_pem_private_key` instead of generating a new one
Real-world use cases
- Automating SSH key pair generation for CI/CD pipeline users on new cloud instances.
- Distributing secure private keys with restricted permissions inside Docker containers for SSH-based services.
- Generating temporary SSH keys for secure file transfers between internal microservices.
Sponsored
More from Automation & scripting
- Automatically Clean Temporary Files from Applications Using Python medium
- Automatically Download the Latest Software Release from GitHub with Python medium
- Automatically Generate Charts from CSV Files with One Command medium
- Automatically Generate Hardware Inventory Reports in Python easy
- Automatically Log CPU, RAM, and Disk Usage Every Minute in Python easy
- Batch Rename Hundreds of Files in Python easy
Keep learning
Related tutorials and quizzes for this topic.