Skip to content

PGP Key Generator — Go source

Generate PGP key pairs (ECC or RSA) in your browser. Download your public and private keys. Powered by OpenPGP.js.

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

// Package pgpkeygen ports src/lib/pgp-keygen.ts (dual source: the web lib is
// TypeScript, the CLI lib is Go — kept in lock-step). The table-driven tests in
// pgp_keygen_test.go share vectors with src/lib/pgp-keygen.test.ts so the two
// implementations are held to the same contract.
//
// The TS lib is a thin wrapper around openpgp.js `generateKey`; this twin
// implements the same OpenPGP surface directly on the Go standard library
// (crypto/ed25519, crypto/rsa) per RFC 4880: v4 key packets, a self-
// certification signature, a standalone revocation signature, ASCII armor with
// CRC-24, and optional passphrase protection of the secret key (S2K usage 254,
// AES-256, iterated-and-salted S2K over SHA-256, CFB mode). Never panics;
// invalid input returns an error.
package pgpkeygen

import (
	"bytes"
	"crypto"
	"crypto/aes"
	"crypto/cipher"
	"crypto/ed25519"
	"crypto/rand"
	"crypto/rsa"
	"crypto/sha1"
	"crypto/sha256"
	"encoding/base64"
	"encoding/binary"
	"encoding/hex"
	"errors"
	"fmt"
	"hash"
	"math/big"
	"regexp"
	"strings"
	"time"
)

// Algorithm choices: ECC Curve25519 (default), RSA-2048, or RSA-4096.
// Mirrors PGPKeyGenAlgorithm in src/lib/pgp-keygen.ts. The zero value means
// ECC — the TS doc comment calls ECC the default curve choice.
type PGPKeyGenAlgorithm string

const (
	// AlgorithmECC is Ed25519/Curve25519 — the default (zero value).
	AlgorithmECC PGPKeyGenAlgorithm = "ecc"
	// AlgorithmRSA2048 is a 2048-bit RSA primary key.
	AlgorithmRSA2048 PGPKeyGenAlgorithm = "rsa2048"
	// AlgorithmRSA4096 is a 4096-bit RSA primary key.
	AlgorithmRSA4096 PGPKeyGenAlgorithm = "rsa4096"
)

// PGPKeyGenOptions configures GeneratePGPKeyPair. Mirrors PGPKeyGenOptions in
// the TS lib; the zero value plus a name/email/algorithm generates a key.
// An empty Passphrase leaves the private key unprotected, matching the TS
// `passphrase ? passphrase : undefined` behavior.
type PGPKeyGenOptions struct {
	// Name goes into the key's user ID packet.
	Name string
	// Email goes into the key's user ID packet.
	Email string
	// Passphrase, if non-empty, encrypts the private key (S2K/AES-256).
	Passphrase string
	// Algorithm picks the primary-key algorithm; "" means ECC.
	Algorithm PGPKeyGenAlgorithm
}

// PGPKeyPair is the generated key material. Mirrors PGPKeyPair in the TS lib.
type PGPKeyPair struct {
	// PublicKey is ASCII-armored (BEGIN PGP PUBLIC KEY BLOCK).
	PublicKey string
	// PrivateKey is ASCII-armored (BEGIN PGP PRIVATE KEY BLOCK).
	PrivateKey string
	// Fingerprint is the v4 fingerprint: 40 lowercase hex chars, no spaces.
	Fingerprint string
	// RevocationCertificate is an ASCII-armored revocation signature.
	RevocationCertificate string
}

// Accepts `foo@bar.tld`-style addresses: one @, non-empty local + domain,
// a dot in the domain. Same regex as EMAIL_RE in the TS lib.
var emailRE = regexp.MustCompile(`^[^\s@]+@[^\s@]+\.[^\s@]+$`)

// ValidateKeyGenIdentity validates the identity that goes into the key's user
// ID. It is the twin of validateKeyGenIdentity in the TS lib and returns the
// exact same error strings.
func ValidateKeyGenIdentity(name, email string) error {
	if strings.TrimSpace(name) == "" {
		return errors.New("Name is required.")
	}
	if strings.TrimSpace(email) == "" {
		return errors.New("Email is required.")
	}
	if !emailRE.MatchString(strings.TrimSpace(email)) {
		return errors.New("Invalid email address.")
	}
	return nil
}

// GeneratePGPKeyPair generates an ASCII-armored PGP key pair. It is the twin
// of generatePGPKeyPair in the TS lib. ECC (Curve25519) is fast; RSA-4096 can
// take a few seconds.
func GeneratePGPKeyPair(options PGPKeyGenOptions) (PGPKeyPair, error) {
	if err := ValidateKeyGenIdentity(options.Name, options.Email); err != nil {
		return PGPKeyPair{}, err
	}

	algo := options.Algorithm
	if algo == "" {
		algo = AlgorithmECC // zero-value default (ECC is the documented default)
	}

	key, err := newKeyMaterial(algo)
	if err != nil {
		return PGPKeyPair{}, err
	}

	// The user ID packet carries the trimmed identity, like the TS lib's
	// `userID = { name: name.trim(), email: email.trim() }`.
	uid := strings.TrimSpace(options.Name) + " <" + strings.TrimSpace(options.Email) + ">"

	// The self-certification signature is shared by the public and private
	// key blocks (standard transferable-key layout).
	cert, err := key.selfCertification(uid)
	if err != nil {
		return PGPKeyPair{}, err
	}

	pubPackets := bytes.Join([][]byte{
		packet(6, key.pubBody()),
		packet(13, []byte(uid)),
		cert,
	}, nil)

	secret, err := key.secretPacket(options.Passphrase)
	if err != nil {
		return PGPKeyPair{}, err
	}
	privPackets := bytes.Join([][]byte{
		secret,
		packet(13, []byte(uid)),
		cert,
	}, nil)

	revocation, err := key.revocationSignature()
	if err != nil {
		return PGPKeyPair{}, err
	}

	return PGPKeyPair{
		PublicKey:             armor("PGP PUBLIC KEY BLOCK", pubPackets),
		PrivateKey:            armor("PGP PRIVATE KEY BLOCK", privPackets),
		Fingerprint:           hex.EncodeToString(key.fingerprint()),
		RevocationCertificate: armor("PGP PUBLIC KEY BLOCK", revocation),
	}, nil
}

// --- public-key algorithm identifiers (RFC 4880 §9.1) ---

const (
	pubAlgoRSA     byte = 1  // RSA (Encrypt or Sign)
	pubAlgoEdDSA   byte = 22 // EdDSA (RFC 4880bis)
	hashAlgoSHA256 byte = 8  // hash algorithm octet for SHA-256
	symAlgoAES256  byte = 9  // symmetric algorithm octet for AES-256
)

// ed25519OID is the Ed25519 curve OID content octets (1.3.6.1.4.1.11591.15.1).
var ed25519OID = []byte{0x2B, 0x06, 0x01, 0x04, 0x01, 0xDA, 0x47, 0x0F, 0x01}

// keyMaterial holds a generated primary key plus its OpenPGP creation time.
type keyMaterial struct {
	created uint32
	algo    byte
	ed      ed25519.PrivateKey // set when algo == pubAlgoEdDSA
	rsa     *rsa.PrivateKey    // set when algo == pubAlgoRSA
}

func newKeyMaterial(algo PGPKeyGenAlgorithm) (*keyMaterial, error) {
	k := &keyMaterial{created: uint32(time.Now().Unix())}
	switch algo {
	case AlgorithmECC:
		_, priv, err := ed25519.GenerateKey(rand.Reader)
		if err != nil {
			return nil, fmt.Errorf("ECC key generation failed: %w", err)
		}
		k.algo, k.ed = pubAlgoEdDSA, priv
	case AlgorithmRSA2048, AlgorithmRSA4096:
		bits := 2048
		if algo == AlgorithmRSA4096 {
			bits = 4096
		}
		priv, err := rsa.GenerateKey(rand.Reader, bits)
		if err != nil {
			return nil, fmt.Errorf("RSA key generation failed: %w", err)
		}
		k.algo, k.rsa = pubAlgoRSA, priv
	default:
		return nil, fmt.Errorf("unknown algorithm %q (want ecc, rsa2048 or rsa4096)", string(algo))
	}
	return k, nil
}

// pubBody serializes the v4 public-key packet body (RFC 4880 §5.5.2).
func (k *keyMaterial) pubBody() []byte {
	body := make([]byte, 0, 64)
	body = append(body, 4) // version
	body = binary.BigEndian.AppendUint32(body, k.created)
	body = append(body, k.algo)
	switch k.algo {
	case pubAlgoEdDSA:
		body = append(body, byte(len(ed25519OID)))
		body = append(body, ed25519OID...)
		// Native point encoding: 0x40 prefix + 32-octet Edwards point.
		point := append([]byte{0x40}, k.ed.Public().(ed25519.PublicKey)...)
		body = append(body, mpi(point)...)
	case pubAlgoRSA:
		body = append(body, mpi(k.rsa.N.Bytes())...)
		body = append(body, mpi(big.NewInt(int64(k.rsa.E)).Bytes())...)
	}
	return body
}

// fingerprint returns the v4 fingerprint: SHA-1 over 0x99 || length || body.
func (k *keyMaterial) fingerprint() []byte {
	body := k.pubBody()
	h := sha1.New()
	h.Write([]byte{0x99, byte(len(body) >> 8), byte(len(body))})
	h.Write(body)
	return h.Sum(nil)
}

// keyID is the low 8 bytes of the v4 fingerprint.
func (k *keyMaterial) keyID() []byte {
	return k.fingerprint()[12:]
}

// secretMPIs serializes the algorithm-specific secret-key material.
// Ed25519: the 32-octet seed. RSA: d, p, q, u with p < q and u = p⁻¹ mod q
// (the OpenPGP CRT convention).
func (k *keyMaterial) secretMPIs() []byte {
	switch k.algo {
	case pubAlgoEdDSA:
		return mpi(k.ed.Seed())
	case pubAlgoRSA:
		p, q := k.rsa.Primes[0], k.rsa.Primes[1]
		if p.Cmp(q) > 0 {
			p, q = q, p
		}
		u := new(big.Int).ModInverse(p, q)
		var out []byte
		out = append(out, mpi(k.rsa.D.Bytes())...)
		out = append(out, mpi(p.Bytes())...)
		out = append(out, mpi(q.Bytes())...)
		out = append(out, mpi(u.Bytes())...)
		return out
	}
	return nil
}

// secretPacket builds the framed secret-key packet (tag 5) plus its trailing
// protection: S2K usage 0 (plaintext + 16-bit checksum) without a passphrase,
// or usage 254 (AES-256 CFB + iterated-salted S2K + SHA-1 integrity) with one.
func (k *keyMaterial) secretPacket(passphrase string) ([]byte, error) {
	pub := k.pubBody()
	mpis := k.secretMPIs()

	if passphrase == "" {
		var sum uint16
		for _, b := range mpis {
			sum += uint16(b)
		}
		body := make([]byte, 0, len(pub)+1+len(mpis)+2)
		body = append(body, pub...)
		body = append(body, 0) // S2K usage: plaintext
		body = append(body, mpis...)
		body = append(body, byte(sum>>8), byte(sum))
		return packet(5, body), nil
	}

	salt := make([]byte, 8)
	if _, err := rand.Read(salt); err != nil {
		return nil, fmt.Errorf("salt generation failed: %w", err)
	}
	const countByte byte = 0x60 // (16+0) << (6+6) = 65536 bytes hashed
	key, err := s2kIteratedKey([]byte(passphrase), salt, s2kCount(countByte), 32, sha256.New)
	if err != nil {
		return nil, err
	}
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, fmt.Errorf("AES cipher init failed: %w", err)
	}
	iv := make([]byte, block.BlockSize())
	if _, err := rand.Read(iv); err != nil {
		return nil, fmt.Errorf("IV generation failed: %w", err)
	}

	// Usage 254 plaintext = secret MPIs || SHA-1(MPIs) (RFC 4880 §5.5.3).
	sha1Sum := sha1.Sum(mpis)
	plain := append(append([]byte{}, mpis...), sha1Sum[:]...)
	encrypted := make([]byte, len(plain))
	cipher.NewCFBEncrypter(block, iv).XORKeyStream(encrypted, plain)

	body := make([]byte, 0, len(pub)+2+len(salt)+1+len(iv)+len(encrypted))
	body = append(body, pub...)
	body = append(body, 254, symAlgoAES256) // S2K usage + symmetric algorithm
	body = append(body, 3, hashAlgoSHA256)  // S2K specifier: iterated+salted, SHA-256
	body = append(body, salt...)
	body = append(body, countByte)
	body = append(body, iv...)
	body = append(body, encrypted...)
	return packet(5, body), nil
}

// s2kCount decodes an S2K count octet: (16 + (c & 15)) << ((c >> 4) + 6).
func s2kCount(c byte) int {
	return (16 + int(c&15)) << ((int(c) >> 4) + 6)
}

// s2kIteratedKey derives a symmetric key per RFC 4880 §3.7.1.4 (iterated and
// salted): each hash context prefixes i zero octets (i = context index) and
// hashes `count` bytes of salt||passphrase repeated.
func s2kIteratedKey(passphrase, salt []byte, count, keyLen int, newHash func() hash.Hash) ([]byte, error) {
	unit := make([]byte, 0, len(salt)+len(passphrase))
	unit = append(unit, salt...)
	unit = append(unit, passphrase...)

	var key []byte
	for ctx := 0; len(key) < keyLen; ctx++ {
		h := newHash()
		for i := 0; i < ctx; i++ {
			h.Write([]byte{0})
		}
		for written := 0; written < count; {
			n := count - written
			if n > len(unit) {
				n = len(unit)
			}
			h.Write(unit[:n])
			written += n
		}
		key = append(key, h.Sum(nil)...)
	}
	return key[:keyLen], nil
}

// subpacket encodes a signature subpacket with a one-octet length. Every
// subpacket this package emits is far below the 192-octet threshold.
func subpacket(typ byte, data []byte) []byte {
	out := make([]byte, 0, len(data)+2)
	out = append(out, byte(len(data)+1), typ)
	return append(out, data...)
}

// signOverKey hashes the signature prefix over the key (and, for
// certifications, the user ID) per RFC 4880 §5.2.4 and signs the digest.
// sigPrefix is the packet body from version through the hashed subpacket area.
func (k *keyMaterial) signOverKey(sigType byte, hashedSubs, extraHashed []byte) (prefix, digest, sigMPI []byte, err error) {
	prefix = []byte{4, sigType, k.algo, hashAlgoSHA256, byte(len(hashedSubs) >> 8), byte(len(hashedSubs))}
	prefix = append(prefix, hashedSubs...)

	pub := k.pubBody()
	h := sha256.New()
	h.Write([]byte{0x99, byte(len(pub) >> 8), byte(len(pub))})
	h.Write(pub)
	h.Write(extraHashed)
	h.Write(prefix)
	h.Write([]byte{4, 0xFF})
	h.Write(binary.BigEndian.AppendUint32(nil, uint32(len(prefix))))
	digest = h.Sum(nil)

	switch k.algo {
	case pubAlgoEdDSA:
		// EdDSA signs the hash output itself (RFC 4880bis §13.3). The
		// signature material is written as TWO MPIs — R, then S — matching
		// what GnuPG emits and parses for EdDSA (verified via gpg
		// --list-packets on a reference ed25519 key).
		sig := ed25519.Sign(k.ed, digest)
		out := mpi(sig[:32])
		out = append(out, mpi(sig[32:])...)
		return prefix, digest, out, nil
	default:
		sig, err := rsa.SignPKCS1v15(nil, k.rsa, crypto.SHA256, digest)
		if err != nil {
			return nil, nil, nil, fmt.Errorf("RSA signing failed: %w", err)
		}
		return prefix, digest, mpi(sig), nil
	}
}

// selfCertification builds the v4 positive-certification signature (type
// 0x13) binding the user ID to the primary key.
func (k *keyMaterial) selfCertification(uid string) ([]byte, error) {
	created := binary.BigEndian.AppendUint32(nil, k.created)
	fp := k.fingerprint()

	hashed := subpacket(2, created)                                     // signature creation time
	hashed = append(hashed, subpacket(27, []byte{0x03})...)             // key flags: certify + sign
	hashed = append(hashed, subpacket(11, []byte{9, 8, 7})...)          // preferred symmetric: AES-256/192/128
	hashed = append(hashed, subpacket(21, []byte{10, 9, 8})...)         // preferred hash: SHA-512/384/256
	hashed = append(hashed, subpacket(22, []byte{2, 1})...)             // preferred compression: zlib, zip
	hashed = append(hashed, subpacket(30, []byte{0x01})...)             // features: modification detection
	hashed = append(hashed, subpacket(33, append([]byte{4}, fp...))...) // issuer fingerprint

	unhashed := subpacket(16, k.keyID()) // issuer key ID

	// Certification hashes 0xB4 || 4-octet length || user ID before the prefix.
	extra := append([]byte{0xB4}, binary.BigEndian.AppendUint32(nil, uint32(len(uid)))...)
	extra = append(extra, uid...)

	prefix, digest, sigMPI, err := k.signOverKey(0x13, hashed, extra)
	if err != nil {
		return nil, err
	}
	return signaturePacket(prefix, unhashed, digest, sigMPI), nil
}

// revocationSignature builds a standalone key-revocation signature (type
// 0x20) over the primary key — the revocation certificate.
func (k *keyMaterial) revocationSignature() ([]byte, error) {
	created := binary.BigEndian.AppendUint32(nil, k.created)
	fp := k.fingerprint()

	hashed := subpacket(2, created)                                     // creation time
	hashed = append(hashed, subpacket(29, []byte{0})...)                // reason: no reason specified
	hashed = append(hashed, subpacket(33, append([]byte{4}, fp...))...) // issuer fingerprint
	unhashed := subpacket(16, k.keyID())

	prefix, digest, sigMPI, err := k.signOverKey(0x20, hashed, nil)
	if err != nil {
		return nil, err
	}
	return signaturePacket(prefix, unhashed, digest, sigMPI), nil
}

// signaturePacket assembles the framed v4 signature packet from its parts.
func signaturePacket(prefix, unhashed, digest, sigMPI []byte) []byte {
	body := make([]byte, 0, len(prefix)+2+len(unhashed)+2+len(sigMPI))
	body = append(body, prefix...)
	body = append(body, byte(len(unhashed)>>8), byte(len(unhashed)))
	body = append(body, unhashed...)
	body = append(body, digest[0], digest[1]) // left 16 bits of the hash
	body = append(body, sigMPI...)
	return packet(2, body)
}

// mpi encodes a multiprecision integer: 2-octet bit count + big-endian value
// with leading zero octets stripped (RFC 4880 §3.2).
func mpi(value []byte) []byte {
	i := 0
	for i < len(value) && value[i] == 0 {
		i++
	}
	value = value[i:]
	if len(value) == 0 {
		return []byte{0, 0}
	}
	bits := len(value)*8 - leadingZeroBits(value[0])
	out := make([]byte, 0, len(value)+2)
	out = binary.BigEndian.AppendUint16(out, uint16(bits))
	return append(out, value...)
}

// leadingZeroBits returns the count of zero bits before the first set bit of b.
func leadingZeroBits(b byte) int {
	switch {
	case b&0x80 != 0:
		return 0
	case b&0x40 != 0:
		return 1
	case b&0x20 != 0:
		return 2
	case b&0x10 != 0:
		return 3
	case b&0x08 != 0:
		return 4
	case b&0x04 != 0:
		return 5
	case b&0x02 != 0:
		return 6
	default:
		return 7
	}
}

// packet frames body in a new-format packet header (RFC 4880 §4.2.2).
func packet(tag byte, body []byte) []byte {
	n := len(body)
	out := make([]byte, 0, n+6)
	out = append(out, 0xC0|tag)
	switch {
	case n < 192:
		out = append(out, byte(n))
	case n < 224:
		v := n - 192
		out = append(out, byte(192+(v>>8)), byte(v))
	default:
		out = append(out, 255)
		out = binary.BigEndian.AppendUint32(out, uint32(n))
	}
	return append(out, body...)
}

// armor wraps binary packet data in ASCII armor (RFC 4880 §6) with the
// CRC-24 checksum line. The final line is the END delimiter.
func armor(blockType string, data []byte) string {
	encoded := base64.StdEncoding.EncodeToString(data)
	var b strings.Builder
	b.WriteString("-----BEGIN " + blockType + "-----\n\n")
	for i := 0; i < len(encoded); i += 64 {
		end := i + 64
		if end > len(encoded) {
			end = len(encoded)
		}
		b.WriteString(encoded[i:end])
		b.WriteByte('\n')
	}
	crc := crc24(data)
	checksum := base64.StdEncoding.EncodeToString([]byte{byte(crc >> 16), byte(crc >> 8), byte(crc)})
	b.WriteString("=" + checksum + "\n")
	b.WriteString("-----END " + blockType + "-----\n")
	return b.String()
}

// crc24 computes the OpenPGP CRC-24 (RFC 4880 §6.1).
func crc24(data []byte) uint32 {
	const (
		init = 0xB704CE
		poly = 0x1864CFB
	)
	crc := uint32(init)
	for _, b := range data {
		crc ^= uint32(b) << 16
		for i := 0; i < 8; i++ {
			crc <<= 1
			if crc&0x1000000 != 0 {
				crc ^= poly
			}
		}
	}
	return crc & 0xFFFFFF
}

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 →