Maintenance

Site is under maintenance — quizzes are still available.

Go to quizzes
Sponsored Reserved space — layout preview until AdSense is connected

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.

Medium Python 3.9+ Jun 28, 2026 Automation & scripting 2 views 0 copies

Requires third-party packages — install first
pip install cryptography

Python code

40 lines
Python 3.9+
import 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

stdout
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

  1. Use `ec` (Elliptic Curve) instead of `rsa` by importing `cryptography.hazmat.primitives.asymmetric.ec`
  2. 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

Sponsored Reserved space — layout preview until AdSense is connected

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from Automation & scripting

Related tutorials and quizzes for this topic.