CSR Generator — Python 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 Python implementation — the same logic the interactive tool runs, in a shareable, citable form.
"""csr-generator — ASN.1 DER encoding + PKCS#10 CSR construction.
Language: Python 3.8+ (standard library only).
CosmoDev polyglot showcase port of the `csr-generator` tool, ported from
src/lib/csr-generator.ts (the canonical TypeScript implementation).
The TS reference generates RSA/EC keys through Web Crypto, which the Python
standard library has no equivalent for. This port therefore implements the
RSA-2048 / RSA-4096 paths end-to-end — Miller-Rabin prime generation, CRT
parameters, RSASSA-PKCS1-v1_5 over SHA-256 via three-arg ``pow()`` — and every
DER byte of the CertificationRequest is assembled by hand, byte-for-byte
compatible with the TypeScript original. ECDSA-P256 needs curve arithmetic the
stdlib lacks, so it raises a clear error (mirroring the Zig port's reverse
choice: there P-256 ships in std and RSA is the unsupported one).
display source — part of CosmoDev's polyglot tool pages.
"""
from __future__ import annotations
import base64
import hashlib
import re
import secrets
import socket
from dataclasses import dataclass, field
# --- options / result ---------------------------------------------------------
@dataclass
class CSROptions:
common_name: str
organization: str = ""
country: str = ""
state: str = ""
locality: str = ""
email: str = ""
key_algorithm: str = "RSA-2048" # 'RSA-2048' | 'RSA-4096' | 'ECDSA-P256'
subject_alt_names: list[str] = field(default_factory=list)
@dataclass
class CSRResult:
csr: str
private_key: str
# --- DER primitives -------------------------------------------------------------
def encode_length(length: int) -> bytes:
"""DER length: short form below 0x80, long form (0x80 | byte count) above."""
if length < 0:
raise ValueError("Length must be a non-negative integer")
if length < 0x80:
return bytes([length])
raw = length.to_bytes((length.bit_length() + 7) // 8, "big")
return bytes([0x80 | len(raw)]) + raw
def _tlv(tag: int, content: bytes) -> bytes:
"""Wrap content bytes in a tag + DER length header."""
return bytes([tag]) + encode_length(len(content)) + content
def encode_integer(value: int | bytes) -> bytes:
"""DER INTEGER: a small non-negative number, or raw big-endian bytes (a
signature half) — leading zeros stripped and a 0x00 sign byte prepended
when the high bit is set, per DER minimal-encoding rules."""
if isinstance(value, int):
if value < 0:
raise ValueError("encode_integer supports non-negative integers only")
raw = value.to_bytes(max(1, (value.bit_length() + 7) // 8), "big")
else:
raw = value.lstrip(b"\x00") or b"\x00"
if raw[0] > 0x7F:
raw = b"\x00" + raw
return _tlv(0x02, raw)
def encode_oid(oid: str) -> bytes:
"""DER OBJECT IDENTIFIER from a dotted string, e.g. '1.2.840.113549.1.1.11'."""
parts = oid.split(".")
if len(parts) < 2 or not all(p.isdigit() for p in parts):
raise ValueError(f"Invalid OID: {oid}")
nums = [int(p) for p in parts]
content = bytearray([40 * nums[0] + nums[1]])
for arc in nums[2:]:
septets: list[int] = []
while True:
septets.insert(0, arc & 0x7F)
arc >>= 7
if not arc:
break
content.extend(b | 0x80 for b in septets[:-1])
content.append(septets[-1])
return _tlv(0x06, bytes(content))
def encode_utf8_string(text: str) -> bytes:
return _tlv(0x0C, text.encode("utf-8"))
def encode_printable_string(text: str) -> bytes:
"""PrintableString — the required type for countryName in a Name."""
if not re.fullmatch(r"[A-Za-z0-9 '()+,\-./:=?]*", text):
raise ValueError(f"Not a PrintableString: {text}")
return _tlv(0x13, text.encode("ascii"))
def encode_bit_string(data: bytes) -> bytes:
return _tlv(0x03, b"\x00" + data) # 0 unused bits in the last octet
def encode_octet_string(data: bytes) -> bytes:
return _tlv(0x04, data)
def encode_null() -> bytes:
return b"\x05\x00"
def encode_sequence(*parts: bytes) -> bytes:
return _tlv(0x30, b"".join(parts))
def encode_set(*parts: bytes) -> bytes:
return _tlv(0x31, b"".join(parts))
def rdn(oid: str, value: bytes) -> bytes:
"""AttributeTypeAndValue (SEQUENCE of OID + value) wrapped in its RDN SET."""
return encode_set(encode_sequence(encode_oid(oid), value))
# --- object identifiers ------------------------------------------------------------
OID_COUNTRY = "2.5.4.6"
OID_STATE = "2.5.4.8"
OID_LOCALITY = "2.5.4.7"
OID_ORGANIZATION = "2.5.4.10"
OID_COMMON_NAME = "2.5.4.3"
OID_EMAIL = "1.2.840.113549.1.9.1"
OID_EXT_REQUEST = "1.2.840.113549.1.9.14" # pkcs-9 at extensionRequest
OID_SUBJECT_ALT_NAME = "2.5.29.17"
OID_RSA_ENCRYPTION = "1.2.840.113549.1.1.1" # rsaEncryption
OID_RSA_SHA256 = "1.2.840.113549.1.1.11" # sha256WithRSAEncryption
# --- validation ----------------------------------------------------------------------
def validate_csr_options(options: CSROptions) -> None:
"""Raises on invalid input: CN required, country (when present) a 2-letter
ISO 3166-1 code, key algorithm one of the supported values."""
if not options.common_name.strip():
raise ValueError("Common Name (CN) is required")
country = options.country.strip()
if country and not re.fullmatch(r"[A-Za-z]{2}", country):
raise ValueError("Country must be a 2-letter ISO 3166-1 code (e.g. US, DE)")
if options.key_algorithm not in ("RSA-2048", "RSA-4096", "ECDSA-P256"):
raise ValueError(f"Unsupported key algorithm: {options.key_algorithm}")
# --- subject alternative names ----------------------------------------------------------
def ip_to_bytes(ip: str) -> bytes | None:
"""Packed 4- or 16-byte address, or None when the entry is not an IP literal."""
for family in (socket.AF_INET, socket.AF_INET6): # IPv4 first, then IPv6 ('::' shorthand OK)
try:
return socket.inet_pton(family, ip)
except OSError:
continue
return None
def classify_san_type(entry: str) -> str:
"""Classify a SAN entry: IPv4/IPv6 -> 'ip', http(s):// -> 'uri', contains an
'@' -> 'email', everything else -> 'dns'."""
value = entry.strip().lower()
if ip_to_bytes(value):
return "ip"
if value.startswith(("http://", "https://")):
return "uri"
if "@" in value:
return "email"
return "dns"
def encode_general_name(entry: str) -> bytes:
"""One GeneralName: context-specific implicit tags per RFC 5280."""
value = entry.strip()
kind = classify_san_type(value)
if kind == "ip":
return _tlv(0x87, ip_to_bytes(value.lower()))
raw = value.encode("utf-8")
return _tlv({"uri": 0x86, "email": 0x81}.get(kind, 0x82), raw) # else dNSName
# --- PEM ------------------------------------------------------------------------------------
def pem_encode(der: bytes, label: str) -> str:
"""PEM-wrap DER bytes: 64-character base64 lines between BEGIN/END markers."""
b64 = base64.b64encode(der).decode("ascii")
lines = [b64[i : i + 64] for i in range(0, len(b64), 64)]
return f"-----BEGIN {label}-----\n" + "\n".join(lines) + f"\n-----END {label}-----\n"
# --- RSA key generation (stdlib has no equivalent of Web Crypto keygen) ----------------------
def _small_primes(limit: int = 1000) -> list[int]:
sieve = bytearray([1]) * (limit + 1)
sieve[0:2] = b"\x00\x00"
for i in range(2, int(limit**0.5) + 1):
if sieve[i]:
sieve[i * i :: i] = bytearray(len(sieve[i * i :: i]))
return [i for i, is_prime in enumerate(sieve) if is_prime]
_SMALL_PRIMES = _small_primes()
def _is_probable_prime(n: int, rounds: int = 24) -> bool:
"""Miller-Rabin with random bases; 24 rounds give an error below 2**-48."""
d, r = n - 1, 0
while d % 2 == 0:
d //= 2
r += 1
for _ in range(rounds):
x = pow(secrets.randbelow(n - 3) + 2, d, n)
if x in (1, n - 1):
continue
for _ in range(r - 1):
x = pow(x, 2, n)
if x == n - 1:
break
else:
return False
return True
def _random_prime(bits: int) -> int:
while True:
candidate = secrets.randbits(bits) | (1 << (bits - 1)) | 1 # top bit set, odd
if all(candidate % p for p in _SMALL_PRIMES) and _is_probable_prime(candidate):
return candidate
def generate_rsa_key(bits: int) -> dict[str, int]:
"""RSA key pair with CRT parameters, e = 65537 — the FIPS 186 shape."""
e = 65537
while True:
p, q = _random_prime(bits // 2), _random_prime(bits // 2)
n = p * q
if p == q or n.bit_length() != bits: # retry until n is exactly `bits` wide
continue
phi = (p - 1) * (q - 1)
if phi % e == 0:
continue
d = pow(e, -1, phi)
return {
"n": n, "e": e, "d": d, "p": p, "q": q,
"dp": d % (p - 1), "dq": d % (q - 1), "qinv": pow(q, -1, p),
}
# RSASSA-PKCS1-v1_5 DigestInfo prefix for SHA-256 (RFC 8017 section 9.2 note 1).
_SHA256_DIGEST_INFO = bytes.fromhex("3031300d060960864801650304020105000420")
def rsa_sign_sha256(key: dict[str, int], message: bytes) -> bytes:
"""RSASSA-PKCS1-v1_5 over SHA-256 — what WebCrypto's RSASSA-PKCS1-v1_5 does."""
k = (key["n"].bit_length() + 7) // 8
t = _SHA256_DIGEST_INFO + hashlib.sha256(message).digest()
em = b"\x00\x01" + b"\xff" * (k - len(t) - 3) + b"\x00" + t
return pow(int.from_bytes(em, "big"), key["d"], key["n"]).to_bytes(k, "big")
def rsa_spki(key: dict[str, int]) -> bytes:
"""SubjectPublicKeyInfo for an RSA key: algorithm + BIT STRING of RSAPublicKey."""
pub = encode_sequence(encode_integer(key["n"]), encode_integer(key["e"]))
alg = encode_sequence(encode_oid(OID_RSA_ENCRYPTION), encode_null())
return encode_sequence(alg, encode_bit_string(pub))
def rsa_pkcs8(key: dict[str, int]) -> bytes:
"""PKCS#8 PrivateKeyInfo wrapping a PKCS#1 RSAPrivateKey — the same
'BEGIN PRIVATE KEY' encoding WebCrypto's exportKey('pkcs8') produces."""
fields = ("n", "e", "d", "p", "q", "dp", "dq", "qinv")
pkcs1 = encode_sequence(encode_integer(0), *(encode_integer(key[f]) for f in fields))
alg = encode_sequence(encode_oid(OID_RSA_ENCRYPTION), encode_null())
return encode_sequence(encode_integer(0), alg, encode_octet_string(pkcs1))
# --- CSR assembly ------------------------------------------------------------------------------
def _subject(options: CSROptions) -> bytes:
"""RDNSequence in the conventional C, ST, L, O, CN, email order."""
rdns: list[bytes] = []
country = options.country.strip().upper()
if country:
rdns.append(rdn(OID_COUNTRY, encode_printable_string(country)))
if options.state.strip():
rdns.append(rdn(OID_STATE, encode_utf8_string(options.state.strip())))
if options.locality.strip():
rdns.append(rdn(OID_LOCALITY, encode_utf8_string(options.locality.strip())))
if options.organization.strip():
rdns.append(rdn(OID_ORGANIZATION, encode_utf8_string(options.organization.strip())))
rdns.append(rdn(OID_COMMON_NAME, encode_utf8_string(options.common_name.strip())))
if options.email.strip():
rdns.append(rdn(OID_EMAIL, encode_utf8_string(options.email.strip())))
return encode_sequence(*rdns)
def _attributes(options: CSROptions) -> bytes:
"""[0] IMPLICIT SET OF Attribute — an extensionRequest carrying the
subjectAltName extension; omitted when no SANs were requested."""
sans = [s.strip() for s in options.subject_alt_names if s.strip()]
if not sans:
return b""
extension = encode_sequence(
encode_oid(OID_SUBJECT_ALT_NAME),
encode_octet_string(encode_sequence(*(encode_general_name(s) for s in sans))),
)
return _tlv(0xA0, encode_sequence(encode_oid(OID_EXT_REQUEST), encode_set(encode_sequence(extension))))
def generate_csr(options: CSROptions) -> CSRResult:
"""Generate a key pair and build a signed PKCS#10 CSR (PEM) plus the
matching PKCS#8 private key (PEM) — same inputs, same DER shape as the TS
original (keys themselves are, of course, freshly random every call)."""
validate_csr_options(options)
if options.key_algorithm == "ECDSA-P256":
raise ValueError(
"ECDSA-P256 is not implemented in the Python stdlib port (the "
"standard library has no curve arithmetic); use RSA-2048 or RSA-4096"
)
key = generate_rsa_key(2048 if options.key_algorithm == "RSA-2048" else 4096)
# CertificationRequestInfo: version 0, subject, SPKI, [0] attributes
cri = encode_sequence(encode_integer(0), _subject(options), rsa_spki(key), _attributes(options))
# signatureAlgorithm + signature over the DER CRI
signature_algorithm = encode_sequence(encode_oid(OID_RSA_SHA256), encode_null())
signature = encode_bit_string(rsa_sign_sha256(key, cri))
return CSRResult(
csr=pem_encode(encode_sequence(cri, signature_algorithm, signature), "CERTIFICATE REQUEST"),
private_key=pem_encode(rsa_pkcs8(key), "PRIVATE KEY"),
)
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 →