Skip to content

CSR Generator — Go source

Generate a Certificate Signing Request and private key pair entirely in your browser. Download the CSR and key as PEM files.

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

// Package csrgenerator ports src/lib/csr-generator.ts (dual source: the web
// lib is TypeScript running on Web Crypto, the CLI lib is Go running on
// crypto/rsa + crypto/ecdsa). Pure + deterministic given a key, never panics.
// The table-driven tests in csr_generator_test.go share vectors with
// src/lib/csr-generator.test.ts so the two implementations are held to the
// same contract.
//
// Pipeline mirrors the TS lib exactly: DER primitives (length/TLV, INTEGER,
// OID, UTF8String, PrintableString, BIT/OCTET STRING, SEQUENCE/SET) → option
// validation → SAN classification (dns/ip/email/uri) → key pair generation →
// RDNSequence assembly (C, ST, L, O, CN, email) → extensionRequest attributes
// → CertificationRequestInfo → signature (sha256WithRSAEncryption or
// ecdsa-with-SHA256) → PEM wrapping.
package csrgenerator

import (
	"crypto"
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/rsa"
	"crypto/sha256"
	"crypto/x509"
	"encoding/base64"
	"errors"
	"fmt"
	"regexp"
	"strconv"
	"strings"
)

// KeyAlgorithm selects the subject key pair type. Mirrors the TS union
// 'RSA-2048' | 'RSA-4096' | 'ECDSA-P256'.
type KeyAlgorithm string

const (
	KeyRSA2048   KeyAlgorithm = "RSA-2048"
	KeyRSA4096   KeyAlgorithm = "RSA-4096"
	KeyECDSAP256 KeyAlgorithm = "ECDSA-P256"
)

// SanType classifies a subjectAltName entry. Mirrors the TS union
// 'dns' | 'ip' | 'email' | 'uri'.
type SanType string

const (
	SanDNS   SanType = "dns"
	SanIP    SanType = "ip"
	SanEmail SanType = "email"
	SanURI   SanType = "uri"
)

// Options configures GenerateCSR. It mirrors the TS CSROptions interface;
// CommonName and KeyAlgorithm are required (the zero value fails
// ValidateCSROptions with the same messages the TS lib throws).
type Options struct {
	CommonName      string
	Organization    string
	Country         string
	State           string
	Locality        string
	Email           string
	KeyAlgorithm    KeyAlgorithm
	SubjectAltNames []string
}

// Result is the generated CSR and its matching private key, both PEM.
// Mirrors the TS CSRResult interface.
type Result struct {
	CSR        string
	PrivateKey string
}

// --- DER primitives ---------------------------------------------------------

// EncodeLength encodes a DER length: short form below 0x80, long form
// (0x80 | byte count) above. It is the Go twin of encodeLength() in
// src/lib/csr-generator.ts.
func EncodeLength(length int) ([]byte, error) {
	if length < 0 {
		return nil, errors.New("Length must be a non-negative integer")
	}
	return derLength(length), nil
}

// derLength is EncodeLength without the error path; callers pass len() ≥ 0.
func derLength(length int) []byte {
	if length < 0x80 {
		return []byte{byte(length)}
	}
	var bytes []byte
	for n := length; n > 0; n >>= 8 {
		bytes = append([]byte{byte(n)}, bytes...)
	}
	return append([]byte{0x80 | byte(len(bytes))}, bytes...)
}

// tlv wraps content bytes in a tag + DER length header. Mirrors tlv().
func tlv(tag byte, content []byte) []byte {
	length := derLength(len(content))
	out := make([]byte, 0, 1+len(length)+len(content))
	out = append(out, tag)
	out = append(out, length...)
	return append(out, content...)
}

// EncodeInteger encodes a small non-negative integer as a DER INTEGER,
// prepending a 0x00 sign byte when the high bit is set (minimal encoding).
// It is the Go twin of the number branch of encodeInteger().
func EncodeInteger(value int) ([]byte, error) {
	if value < 0 {
		return nil, errors.New("encodeInteger supports non-negative integers only")
	}
	var digits []byte
	for n := value; n > 0; n >>= 8 {
		digits = append([]byte{byte(n)}, digits...)
	}
	if len(digits) == 0 {
		digits = []byte{0}
	}
	return tlv(0x02, withSignByte(digits)), nil
}

// EncodeIntegerBytes encodes raw big-endian bytes (signature r/s halves) as a
// DER INTEGER: leading zeros are stripped, then a 0x00 sign byte is prepended
// when the high bit is set. It is the Go twin of the Uint8Array branch of
// encodeInteger(); it never fails.
func EncodeIntegerBytes(value []byte) []byte {
	start := 0
	for start < len(value)-1 && value[start] == 0 {
		start++
	}
	return tlv(0x02, withSignByte(value[start:]))
}

// withSignByte prepends the DER sign byte when the high bit is set. An empty
// input stays empty (mirrors bytes[0] === undefined in the TS lib).
func withSignByte(b []byte) []byte {
	if len(b) > 0 && b[0] > 0x7f {
		return append([]byte{0}, b...)
	}
	return b
}

// EncodeOID encodes a dotted OID string (e.g. '1.2.840.113549.1.1.11') as a
// DER OBJECT IDENTIFIER. It is the Go twin of encodeOID().
func EncodeOID(oid string) ([]byte, error) {
	parts := strings.Split(oid, ".")
	if len(parts) < 2 {
		return nil, fmt.Errorf("Invalid OID: %s", oid)
	}
	values := make([]uint64, len(parts))
	for i, p := range parts {
		v, err := strconv.ParseUint(p, 10, 32)
		if err != nil {
			return nil, fmt.Errorf("Invalid OID: %s", oid)
		}
		values[i] = v
	}
	content := []byte{byte(40*values[0] + values[1])}
	for _, v := range values[2:] {
		var stack []byte
		for {
			stack = append([]byte{byte(v & 0x7f)}, stack...)
			v >>= 7
			if v == 0 {
				break
			}
		}
		for j := 0; j < len(stack)-1; j++ {
			stack[j] |= 0x80
		}
		content = append(content, stack...)
	}
	return tlv(0x06, content), nil
}

// EncodeUTF8String encodes a UTF-8 string as a DER UTF8String (tag 0x0c).
// It is the Go twin of encodeUTF8String().
func EncodeUTF8String(str string) []byte {
	return tlv(0x0c, []byte(str))
}

// EncodePrintableString encodes an ASCII PrintableString (tag 0x13) — the
// required type for countryName in a Name. It is the Go twin of
// encodePrintableString() and rejects the same character set.
func EncodePrintableString(str string) ([]byte, error) {
	for _, r := range str {
		if !isPrintableRune(r) {
			return nil, fmt.Errorf("Not a PrintableString: %s", str)
		}
	}
	return tlv(0x13, []byte(str)), nil
}

// isPrintableRune reports membership in the TS lib's PrintableString regex
// ^[A-Za-z0-9 '()+,\-./:=?]*$ — an ASCII-only set.
func isPrintableRune(r rune) bool {
	switch {
	case r >= 'A' && r <= 'Z', r >= 'a' && r <= 'z', r >= '0' && r <= '9':
		return true
	}
	switch r {
	case ' ', '\'', '(', ')', '+', ',', '-', '.', '/', ':', '=', '?':
		return true
	}
	return false
}

// EncodeBitString encodes data as a DER BIT STRING with 0 unused bits in the
// leading octet. It is the Go twin of encodeBitString().
func EncodeBitString(data []byte) []byte {
	content := append([]byte{0}, data...)
	return tlv(0x03, content)
}

// EncodeOctetString encodes data as a DER OCTET STRING (tag 0x04).
// It is the Go twin of encodeOctetString().
func EncodeOctetString(data []byte) []byte {
	return tlv(0x04, data)
}

// EncodeNull returns the DER NULL encoding. Mirrors encodeNull().
func EncodeNull() []byte {
	return []byte{0x05, 0x00}
}

// EncodeSequence concatenates parts and wraps them in a SEQUENCE (tag 0x30).
// It is the Go twin of encodeSequence().
func EncodeSequence(parts ...[]byte) []byte {
	return tlv(0x30, concat(parts))
}

// EncodeSet concatenates parts and wraps them in a SET (tag 0x31).
// It is the Go twin of encodeSet().
func EncodeSet(parts ...[]byte) []byte {
	return tlv(0x31, concat(parts))
}

func concat(parts [][]byte) []byte {
	var out []byte
	for _, p := range parts {
		out = append(out, p...)
	}
	return out
}

// --- Object identifiers (DER literals, cross-checked by the OID vectors) ----

var (
	oidCountry       = []byte{0x06, 0x03, 0x55, 0x04, 0x06}                                     // 2.5.4.6
	oidState         = []byte{0x06, 0x03, 0x55, 0x04, 0x08}                                     // 2.5.4.8
	oidLocality      = []byte{0x06, 0x03, 0x55, 0x04, 0x07}                                     // 2.5.4.7
	oidOrganization  = []byte{0x06, 0x03, 0x55, 0x04, 0x0a}                                     // 2.5.4.10
	oidCommonName    = []byte{0x06, 0x03, 0x55, 0x04, 0x03}                                     // 2.5.4.3
	oidEmail         = []byte{0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x01} // 1.2.840.113549.1.9.1
	oidExtRequest    = []byte{0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x0e} // 1.2.840.113549.1.9.14 pkcs-9 at extensionRequest
	oidSubjectAltNam = []byte{0x06, 0x03, 0x55, 0x1d, 0x11}                                     // 2.5.29.17
	oidRSASHA256     = []byte{0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b} // 1.2.840.113549.1.1.11 sha256WithRSAEncryption
	oidECDSASHA256   = []byte{0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02}       // 1.2.840.10045.4.3.2 ecdsa-with-SHA256
)

// --- Validation --------------------------------------------------------------

// ValidateCSROptions returns an error on invalid input: CN required, country
// (when present) a 2-letter ISO 3166-1 code, key algorithm one of the
// supported values. It is the Go twin of validateCSROptions() and carries the
// same messages.
func ValidateCSROptions(options Options) error {
	if strings.TrimSpace(options.CommonName) == "" {
		return errors.New("Common Name (CN) is required")
	}
	if country := strings.TrimSpace(options.Country); country != "" && !twoLetterCountry.MatchString(country) {
		return errors.New("Country must be a 2-letter ISO 3166-1 code (e.g. US, DE)")
	}
	switch options.KeyAlgorithm {
	case KeyRSA2048, KeyRSA4096, KeyECDSAP256:
	default:
		return fmt.Errorf("Unsupported key algorithm: %s", options.KeyAlgorithm)
	}
	return nil
}

var twoLetterCountry = regexp.MustCompile(`^[A-Za-z]{2}$`)

// --- SAN classification ------------------------------------------------------

// ClassifySanType classifies a SAN entry: IPv4/IPv6 → ip, http(s):// → uri,
// contains @ → email, else dns. It is the Go twin of classifySanType().
func ClassifySanType(entry string) SanType {
	value := strings.ToLower(strings.TrimSpace(entry))
	if ipToBytes(value) != nil {
		return SanIP
	}
	if uriPrefix.MatchString(value) {
		return SanURI
	}
	if strings.Contains(value, "@") {
		return SanEmail
	}
	return SanDNS
}

var (
	uriPrefix   = regexp.MustCompile(`^https?://`)
	ipv4Re      = regexp.MustCompile(`^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$`)
	ipv6GroupRe = regexp.MustCompile(`^[0-9a-f]{1,4}$`)
)

// ipToBytes parses an IPv4 or IPv6 literal (already lowercased) to its 4- or
// 16-byte form, or nil when the literal is malformed. It mirrors ipToBytes()
// in the TS lib, including the IPv4-mapped-tail handling and the ::-run rules.
func ipToBytes(ip string) []byte {
	if m := ipv4Re.FindStringSubmatch(ip); m != nil {
		out := make([]byte, 4)
		for i := 1; i <= 4; i++ {
			n, _ := strconv.Atoi(m[i]) // regex guarantees 1-3 ASCII digits
			if n > 255 {
				return nil
			}
			out[i-1] = byte(n)
		}
		return out
	}
	if !strings.Contains(ip, ":") {
		return nil
	}
	halves := strings.Split(ip, "::")
	if len(halves) > 2 {
		return nil
	}
	var groups []int
	for _, half := range halves {
		if half == "" {
			continue
		}
		for _, group := range strings.Split(half, ":") {
			if strings.Contains(group, ".") {
				tail := ipToBytes(group) // IPv4-mapped tail, e.g. ::ffff:10.0.0.1
				if tail == nil || len(tail) != 4 {
					return nil
				}
				groups = append(groups, int(tail[0])<<8|int(tail[1]), int(tail[2])<<8|int(tail[3]))
			} else if ipv6GroupRe.MatchString(group) {
				v, _ := strconv.ParseInt(group, 16, 32) // regex guarantees 1-4 hex digits
				groups = append(groups, int(v))
			} else {
				return nil
			}
		}
	}
	if len(halves) == 2 {
		missing := 8 - len(groups)
		if missing < 0 {
			return nil
		}
		for range missing {
			groups = append(groups, 0)
		}
	}
	if len(groups) != 8 {
		return nil
	}
	out := make([]byte, 16)
	for i, g := range groups {
		out[i*2] = byte(g >> 8)
		out[i*2+1] = byte(g & 0xff)
	}
	return out
}

// encodeGeneralName encodes one GeneralName with context-specific implicit
// tags per RFC 5280. It mirrors encodeGeneralName() in the TS lib.
func encodeGeneralName(entry string) []byte {
	value := strings.TrimSpace(entry)
	ascii := []byte(value)
	switch ClassifySanType(value) {
	case SanIP:
		return tlv(0x87, ipToBytes(strings.ToLower(value)))
	case SanURI:
		return tlv(0x86, ascii)
	case SanEmail:
		return tlv(0x81, ascii)
	default:
		return tlv(0x82, ascii) // dNSName
	}
}

// --- PEM ----------------------------------------------------------------------

// PemEncode PEM-wraps DER bytes: 64-character base64 lines between BEGIN/END
// markers. It is the Go twin of pemEncode(), including the empty-body shape
// for zero-length DER (an empty line between the markers).
func PemEncode(der []byte, label string) string {
	b64 := base64.StdEncoding.EncodeToString(der)
	var lines []string
	for len(b64) > 64 {
		lines = append(lines, b64[:64])
		b64 = b64[64:]
	}
	if len(b64) > 0 {
		lines = append(lines, b64)
	}
	body := strings.Join(lines, "\n") // no lines → empty body line, as in the TS join
	return "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n"
}

// --- Key generation + CSR assembly --------------------------------------------

// rdn wraps an AttributeTypeAndValue (SEQUENCE of OID + value) in its RDN SET.
// It mirrors rdn() in the TS lib.
func rdn(oid, value []byte) []byte {
	return EncodeSet(EncodeSequence(oid, value))
}

// GenerateCSR generates a key pair and builds a signed PKCS#10 CSR (PEM) plus
// the matching PKCS#8 private key (PEM). It is the Go twin of generateCSR(),
// running on crypto/rsa + crypto/ecdsa instead of Web Crypto.
func GenerateCSR(options Options) (Result, error) {
	if err := ValidateCSROptions(options); err != nil {
		return Result{}, err
	}

	var (
		rsaKey *rsa.PrivateKey
		ecKey  *ecdsa.PrivateKey
		spki   []byte
		pkcs8  []byte
		err    error
	)
	switch options.KeyAlgorithm {
	case KeyECDSAP256:
		if ecKey, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader); err != nil {
			return Result{}, fmt.Errorf("generate P-256 key pair: %w", err)
		}
		spki, err = x509.MarshalPKIXPublicKey(&ecKey.PublicKey)
	default: // RSA-2048 / RSA-4096 — ValidateCSROptions narrowed the field
		bits := 2048
		if options.KeyAlgorithm == KeyRSA4096 {
			bits = 4096
		}
		if rsaKey, err = rsa.GenerateKey(rand.Reader, bits); err != nil {
			return Result{}, fmt.Errorf("generate RSA-%d key pair: %w", bits, err)
		}
		spki, err = x509.MarshalPKIXPublicKey(&rsaKey.PublicKey)
	}
	if err != nil {
		return Result{}, fmt.Errorf("marshal public key: %w", err)
	}
	if ecKey != nil {
		pkcs8, err = x509.MarshalPKCS8PrivateKey(ecKey)
	} else {
		pkcs8, err = x509.MarshalPKCS8PrivateKey(rsaKey)
	}
	if err != nil {
		return Result{}, fmt.Errorf("marshal private key: %w", err)
	}

	// subject: RDNSequence in the conventional C, ST, L, O, CN, email order
	var rdns [][]byte
	if country := strings.ToUpper(strings.TrimSpace(options.Country)); country != "" {
		printable, err := EncodePrintableString(country)
		if err != nil {
			return Result{}, err
		}
		rdns = append(rdns, rdn(oidCountry, printable))
	}
	if v := strings.TrimSpace(options.State); v != "" {
		rdns = append(rdns, rdn(oidState, EncodeUTF8String(v)))
	}
	if v := strings.TrimSpace(options.Locality); v != "" {
		rdns = append(rdns, rdn(oidLocality, EncodeUTF8String(v)))
	}
	if v := strings.TrimSpace(options.Organization); v != "" {
		rdns = append(rdns, rdn(oidOrganization, EncodeUTF8String(v)))
	}
	rdns = append(rdns, rdn(oidCommonName, EncodeUTF8String(strings.TrimSpace(options.CommonName))))
	if v := strings.TrimSpace(options.Email); v != "" {
		rdns = append(rdns, rdn(oidEmail, EncodeUTF8String(v)))
	}

	// attributes [0] IMPLICIT SET OF — extensionRequest carrying subjectAltName
	var attributes []byte
	var sans []string
	for _, s := range options.SubjectAltNames {
		if v := strings.TrimSpace(s); v != "" {
			sans = append(sans, v)
		}
	}
	if len(sans) > 0 {
		names := make([][]byte, len(sans))
		for i, s := range sans {
			names[i] = encodeGeneralName(s)
		}
		extension := EncodeSequence(
			oidSubjectAltNam,
			EncodeOctetString(EncodeSequence(names...)),
		)
		attribute := EncodeSequence(
			oidExtRequest,
			EncodeSet(EncodeSequence(extension)),
		)
		attributes = tlv(0xa0, attribute) // [0] IMPLICIT SET OF Attribute
	}

	// CertificationRequestInfo: version 0, subject, SPKI, [0] attributes.
	// The version literal is the DER INTEGER 0 pinned by the TS suite.
	// Interop note: like the TS lib (and unlike openssl), the [0] tag is
	// omitted entirely when there are no SANs — RFC 2986-lenient parsers
	// accept this, but Go's x509.ParseCertificateRequest rejects it, so the
	// Go twin keeps the TS shape and callers verify signatures directly.
	cri := EncodeSequence([]byte{0x02, 0x01, 0x00}, EncodeSequence(rdns...), spki, attributes)

	// signatureAlgorithm + signature over the DER CRI
	var signatureAlgorithm, signature []byte
	if options.KeyAlgorithm == KeyECDSAP256 {
		signatureAlgorithm = EncodeSequence(oidECDSASHA256)
		derSig, err := ecdsa.SignASN1(rand.Reader, ecKey, cri)
		if err != nil {
			return Result{}, fmt.Errorf("sign CSR: %w", err)
		}
		// ecdsa.SignASN1 emits the DER ECDSA-Sig-Value SEQUENCE directly —
		// what the TS lib builds from Web Crypto's raw r||s via ecdsaRawToDer.
		signature = EncodeBitString(derSig)
	} else {
		signatureAlgorithm = EncodeSequence(oidRSASHA256, EncodeNull())
		digest := sha256.Sum256(cri)
		sig, err := rsa.SignPKCS1v15(rand.Reader, rsaKey, crypto.SHA256, digest[:])
		if err != nil {
			return Result{}, fmt.Errorf("sign CSR: %w", err)
		}
		signature = EncodeBitString(sig)
	}

	return Result{
		CSR:        PemEncode(EncodeSequence(cri, signatureAlgorithm, signature), "CERTIFICATE REQUEST"),
		PrivateKey: PemEncode(pkcs8, "PRIVATE KEY"),
	}, nil
}

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 →