Skip to content

SSH Key Generator — Python source

Generate Ed25519 or RSA SSH key pairs in your browser. Copy or download the public and private keys. No server involved.

This is the Python implementation — the same logic the interactive tool runs, in a shareable, citable form.

"""ssh-keygen — Ed25519 SSH key pair generation in OpenSSH format.

Language: Python 3 (standard library only).
CosmoDev polyglot showcase port of the `ssh-keygen` tool, ported from
src/lib/ssh-keygen.ts (the canonical TypeScript implementation).

Python's standard library ships no asymmetric key generation, so the Ed25519
key math is implemented inline (RFC 8032 Edwards-curve arithmetic over plain
``int`` field elements) while the RSA options are reported as unsupported —
mirroring the Zig sibling; an RSA port would need a third-party library.

display source — part of CosmoDev's polyglot tool pages.
"""

from __future__ import annotations

import base64
import hashlib
import secrets

_P = 2**255 - 19                                # the field of Curve25519
_I = pow(2, (_P - 1) // 4, _P)                  # sqrt(-1) mod p
_D = -121665 * pow(121666, _P - 2, _P) % _P     # the curve constant d

# ---- Ed25519 core (RFC 8032) -----------------------------------------------


def _inv(x: int) -> int:
    """Multiplicative inverse in the field, via Fermat's little theorem."""
    return pow(x, _P - 2, _P)


def _edwards_add(p, q):
    """Add two points in affine twisted-Edwards form (x, y)."""
    (x1, y1), (x2, y2) = p, q
    k = _D * x1 * x2 * y1 * y2
    x3 = (x1 * y2 + x2 * y1) * _inv(1 + k)
    y3 = (y1 * y2 + x1 * x2) * _inv(1 - k)
    return x3 % _P, y3 % _P


def _scalarmult(p, e: int):
    """Double-and-add scalar multiplication, q = e * p."""
    q = (0, 1)  # the identity element
    while e > 0:
        if e & 1:
            q = _edwards_add(q, p)
        p = _edwards_add(p, p)
        e >>= 1
    return q


def _recover_x(y: int, sign: int) -> int:
    """Solve the curve equation -x^2 + y^2 = 1 + d*x^2*y^2 for x, choosing the
    parity `sign` of the root."""
    x2 = (y * y - 1) * _inv(_D * y * y + 1)
    x = pow(x2, (_P + 3) // 8, _P)
    if (x * x - x2) % _P != 0:
        x = x * _I % _P
    if (x * x - x2) % _P != 0:
        raise ValueError('invalid point encoding')
    return _P - x if x & 1 != sign else x


_BY = 4 * _inv(5) % _P          # base point: y = 4/5, x even (per RFC 8032)
_B = (_recover_x(_BY, 0), _BY)


def _encode_point(p) -> bytes:
    """RFC 8032 point encoding: little-endian y, sign of x folded into bit 255."""
    x, y = p
    out = bytearray(y.to_bytes(32, 'little'))
    out[31] |= (x & 1) << 7
    return bytes(out)


def _public_from_seed(seed: bytes) -> bytes:
    """Derive the 32-byte Ed25519 public key from a 32-byte seed (RFC 8032 §5.1)."""
    h = hashlib.sha512(seed).digest()
    a = int.from_bytes(h[:32], 'little')
    a = a & ((1 << 254) - 8) | 1 << 254  # clamp: clear the low 3 bits, set bit 254
    return _encode_point(_scalarmult(_B, a))


# ---- SSH wire format --------------------------------------------------------


def _u32(n: int) -> bytes:
    return n.to_bytes(4, 'big')


def _ssh_string(data: bytes | str) -> bytes:
    """SSH "string": 4-byte big-endian length + raw bytes."""
    if isinstance(data, str):
        data = data.encode('utf-8')
    return _u32(len(data)) + data


def _mpint(data: bytes) -> bytes:
    """SSH "mpint": big-endian integer, minimal, with a leading 0x00 when the
    high bit is set. (Kept for parity with the TypeScript lib's RSA path.)"""
    i = 0
    while i + 1 < len(data) and data[i] == 0:
        i += 1
    v = data[i:]
    if v and v[0] & 0x80:
        v = b'\x00' + v
    return _ssh_string(v)


def _b64(data: bytes) -> str:
    return base64.b64encode(data).decode('ascii')


def _pem_wrap(b64_text: str, label: str, width: int) -> str:
    lines = [b64_text[i : i + width] for i in range(0, len(b64_text), width)]
    return f'-----BEGIN {label}-----\n' + '\n'.join(lines) + f'\n-----END {label}-----\n'


def _fingerprint(pub_blob: bytes) -> str:
    """SHA256:<base64 digest of the public blob, unpadded> - OpenSSH format."""
    return 'SHA256:' + _b64(hashlib.sha256(pub_blob).digest()).rstrip('=')


def _openssh_private_pem(pub_blob: bytes, private_key: bytes, comment: str) -> str:
    """Build the unencrypted "openssh-key-v1" private key structure (cipher
    "none", kdf "none"), wrapped in an OPENSSH PRIVATE KEY PEM."""
    check = secrets.token_bytes(4)
    inner = check + check + pub_blob + _ssh_string(private_key) + _ssh_string(comment)
    inner += bytes(range(1, (8 - len(inner) % 8) % 8 + 1))  # pad with 1,2,3,...
    outer = (
        b'openssh-key-v1\x00'
        + _ssh_string('none')           # ciphername
        + _ssh_string('none')           # kdfname
        + _ssh_string(b'')              # kdfoptions
        + _u32(1)                       # number of keys
        + _ssh_string(pub_blob)
        + _ssh_string(inner)
    )
    return _pem_wrap(_b64(outer), 'OPENSSH PRIVATE KEY', 70)


# ---- public API --------------------------------------------------------------


def generate_ssh_key_pair(options: dict | None = None) -> dict:
    """Generate an SSH key pair in OpenSSH format.

    ``options`` holds ``algorithm`` ("ed25519", "rsa-2048" or "rsa-4096") and
    an optional ``comment`` (conventionally ``user@host``, omitted when
    empty). Returns ``{"public_key", "private_key", "fingerprint"}``.
    """
    opts = options or {}
    algorithm = opts.get('algorithm')
    comment = (opts.get('comment') or '').strip()
    suffix = f' {comment}' if comment else ''

    if algorithm == 'ed25519':
        seed = secrets.token_bytes(32)
        pub = _public_from_seed(seed)
        pub_blob = _ssh_string('ssh-ed25519') + _ssh_string(pub)
        return {
            'public_key': f'ssh-ed25519 {_b64(pub_blob)}{suffix}',
            'private_key': _openssh_private_pem(pub_blob, seed + pub, comment),
            'fingerprint': _fingerprint(pub_blob),
        }
    if algorithm in ('rsa-2048', 'rsa-4096'):
        raise ValueError(
            f'{algorithm}: the Python standard library has no RSA key generator; '
            'this port implements the Ed25519 path natively (see the Zig sibling).'
        )
    raise ValueError(f'Unsupported algorithm: {algorithm}')

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →