SSH Key Generator — Go 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 Go implementation — the same logic the interactive tool runs, in a shareable, citable form.
// Package sshkeygen ports src/lib/ssh-keygen.ts — the Go twin of CosmoDev's
// SSH key generator (dual source: the web lib is TypeScript, the CLI lib is
// Go — kept in lock-step). Pure library: keys are generated with the Go
// crypto stack and encoded in OpenSSH formats; nothing leaves the process.
// The table-driven tests in ssh_keygen_test.go share vectors with
// src/lib/ssh-keygen.test.ts so both implementations are held to one contract.
//
// Formats produced (identical to the TS lib):
// - Ed25519 public key : "ssh-ed25519 <base64(blob)> <comment>" where blob
// is the OpenSSH wire format (string "ssh-ed25519" + string 32-byte key).
// - Ed25519 private key: "-----BEGIN OPENSSH PRIVATE KEY-----" PEM containing
// the unencrypted "openssh-key-v1" structure (cipher "none", kdf "none").
// - RSA public key : "ssh-rsa <base64(blob)> <comment>" where blob is
// string "ssh-rsa" + mpint e + mpint n.
// - RSA private key : PKCS#8 PEM ("-----BEGIN PRIVATE KEY-----").
// - Fingerprint : SHA-256 of the raw public key blob, base64-encoded
// without padding, prefixed "SHA256:" (matches OpenSSH).
package sshkeygen
import (
"crypto/ed25519"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/binary"
"fmt"
"math/big"
"strings"
)
// Algorithm selects the key type. It mirrors SSHAlgorithm in the TS lib.
type Algorithm string
const (
Ed25519 Algorithm = "ed25519"
RSA2048 Algorithm = "rsa-2048"
RSA4096 Algorithm = "rsa-4096"
)
// Options configures GenerateKeyPair. The zero value carries no algorithm and
// is rejected — mirroring generateSSHKeyPair() called with no options in the
// TS lib. Comment is optional and conventionally "user@host"; it is trimmed
// and omitted from the public line when empty.
type Options struct {
Algorithm Algorithm
Comment string
}
// KeyPair is the generated OpenSSH key material. It mirrors SSHKeyPair.
type KeyPair struct {
PublicKey string
PrivateKey string
Fingerprint string
}
// magic is the "openssh-key-v1\0" prefix of the OpenSSH private key format.
var magic = []byte("openssh-key-v1\x00")
// concat joins byte slices, mirroring concat() in the TS lib.
func concat(parts ...[]byte) []byte {
n := 0
for _, p := range parts {
n += len(p)
}
out := make([]byte, 0, n)
for _, p := range parts {
out = append(out, p...)
}
return out
}
// u32 encodes n as a 4-byte big-endian uint, mirroring u32() in the TS lib.
func u32(n uint32) []byte {
var b [4]byte
binary.BigEndian.PutUint32(b[:], n)
return b[:]
}
// sshString encodes an SSH "string": 4-byte big-endian length + raw bytes.
func sshString(data []byte) []byte {
return append(u32(uint32(len(data))), data...)
}
// sshStringS is sshString for text.
func sshStringS(s string) []byte {
return append(u32(uint32(len(s))), s...)
}
// mpint encodes an SSH "mpint": big-endian integer, minimal, with a leading
// zero when the high bit is set. Mirrors mpint() in the TS lib.
func mpint(bytes []byte) []byte {
i := 0
for i < len(bytes)-1 && bytes[i] == 0 {
i++
}
v := bytes[i:]
if len(v) > 0 && v[0]&0x80 != 0 {
return sshString(concat([]byte{0}, v))
}
return sshString(v)
}
// pemWrap wraps a base64 body in PEM armor at the given line width. Mirrors
// pemWrap() in the TS lib (Go's encoding/pem is fixed at 64; the OpenSSH
// private key format uses 70).
func pemWrap(b64, label string, width int) string {
var lines []string
for len(b64) > width {
lines = append(lines, b64[:width])
b64 = b64[width:]
}
if len(b64) > 0 {
lines = append(lines, b64)
}
return "-----BEGIN " + label + "-----\n" + strings.Join(lines, "\n") + "\n-----END " + label + "-----\n"
}
// fingerprint returns "SHA256:<base64 digest of the public blob, unpadded>" —
// the OpenSSH fingerprint format. Mirrors sshFingerprint() in the TS lib.
func fingerprint(pubBlob []byte) string {
sum := sha256.Sum256(pubBlob)
return "SHA256:" + strings.TrimRight(base64.StdEncoding.EncodeToString(sum[:]), "=")
}
// openSshPrivatePem builds the unencrypted "openssh-key-v1" private key
// structure (cipher "none", kdf "none") and wraps it in an OPENSSH PRIVATE
// KEY PEM. Mirrors openSshPrivatePem() in the TS lib.
func openSshPrivatePem(pubBlob, privateKeyBytes []byte, comment string) (string, error) {
var check [4]byte
if _, err := rand.Read(check[:]); err != nil {
return "", fmt.Errorf("reading checkint randomness: %w", err)
}
inner := concat(check[:], check[:], pubBlob, sshString(privateKeyBytes), sshStringS(comment))
// Pad to a multiple of the block size (8 for cipher "none") with 1,2,3,...
padLen := (8 - len(inner)%8) % 8
padding := make([]byte, padLen)
for i := range padding {
padding[i] = byte(i + 1)
}
outer := concat(
magic,
sshStringS("none"), // ciphername
sshStringS("none"), // kdfname
sshString(nil), // kdfoptions
u32(1), // number of keys
sshString(pubBlob), // public key section
sshString(concat(inner, padding)),
)
return pemWrap(base64.StdEncoding.EncodeToString(outer), "OPENSSH PRIVATE KEY", 70), nil
}
// GenerateKeyPair generates an SSH key pair in OpenSSH format. It is the Go
// twin of generateSSHKeyPair() in src/lib/ssh-keygen.ts and must agree with
// it on every shared vector. It never panics; invalid input returns an error.
func GenerateKeyPair(opts Options) (KeyPair, error) {
comment := strings.TrimSpace(opts.Comment)
suffix := ""
if comment != "" {
suffix = " " + comment
}
switch opts.Algorithm {
case Ed25519:
pub, priv, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
return KeyPair{}, fmt.Errorf("generating Ed25519 key: %w", err)
}
if len(pub) != ed25519.PublicKeySize {
return KeyPair{}, fmt.Errorf("unexpected Ed25519 public key length: %d", len(pub))
}
if len(priv) != ed25519.PrivateKeySize {
return KeyPair{}, fmt.Errorf("unexpected Ed25519 private key encoding")
}
// ed25519.PrivateKey is seed || public key — the same seed||pub layout
// the TS lib extracts from the PKCS#8 wrapper.
seed := priv[:32]
pubBlob := concat(sshStringS("ssh-ed25519"), sshString(pub))
privatePEM, err := openSshPrivatePem(pubBlob, concat(seed, pub), comment)
if err != nil {
return KeyPair{}, err
}
return KeyPair{
PublicKey: "ssh-ed25519 " + base64.StdEncoding.EncodeToString(pubBlob) + suffix,
PrivateKey: privatePEM,
Fingerprint: fingerprint(pubBlob),
}, nil
case RSA2048, RSA4096:
bits := 2048
if opts.Algorithm == RSA4096 {
bits = 4096
}
priv, err := rsa.GenerateKey(rand.Reader, bits)
if err != nil {
return KeyPair{}, fmt.Errorf("generating RSA-%d key: %w", bits, err)
}
pubBlob := concat(
sshStringS("ssh-rsa"),
mpint(new(big.Int).SetInt64(int64(priv.E)).Bytes()),
mpint(priv.N.Bytes()),
)
pkcs8, err := x509.MarshalPKCS8PrivateKey(priv)
if err != nil {
return KeyPair{}, fmt.Errorf("encoding RSA private key as PKCS#8: %w", err)
}
return KeyPair{
PublicKey: "ssh-rsa " + base64.StdEncoding.EncodeToString(pubBlob) + suffix,
PrivateKey: pemWrap(base64.StdEncoding.EncodeToString(pkcs8), "PRIVATE KEY", 64),
Fingerprint: fingerprint(pubBlob),
}, nil
}
return KeyPair{}, fmt.Errorf("unsupported algorithm: %q", string(opts.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 →