Skip to content

CSR Generator — Rust 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 Rust implementation — the same logic the interactive tool runs, in a shareable, citable form.

//! csr-generator — ASN.1 DER encoding + PKCS#10 CSR construction.
//!
//! Language: Rust (std only — no external crates).
//! CosmoDev polyglot showcase port of the `csr-generator` tool, ported from
//! src/lib/csr-generator.ts (the canonical TypeScript implementation).
//!
//! Why this file exists: every DER byte of the CertificationRequest — length
//! headers, INTEGER/OID/string primitives, the RDN sequence, the
//! extensionRequest SAN attribute — is assembled by hand, byte-for-byte
//! compatible with the TS original. Rust std has no Web Crypto equivalent (no
//! RSA/EC keygen, SHA-256, or bignum arithmetic), so that half is injected
//! rather than faked: `generate_csr` takes the raw SPKI/PKCS#8 key exports and
//! a signing closure — the role `crypto.subtle` plays in the TS lib. Std does
//! ship `IpAddr`, so the SAN IP check is a `parse`, not the TS hand-rolled
//! IPv4/IPv6 reader.
//!
//! display source — part of CosmoDev's polyglot tool pages.

/// Key algorithms accepted by the tool. The TS port runtime-checks this string;
/// Rust's enum makes an invalid choice unrepresentable.
#[derive(Clone, Copy, PartialEq, Eq, Default)]
pub enum KeyAlgorithm {
    #[default]
    Rsa2048,
    Rsa4096,
    EcdsaP256,
}

/// Options, mirroring `CSROptions` in the TS lib (empty string = omitted).
#[derive(Default)]
pub struct CsrOptions<'a> {
    pub common_name: &'a str,
    pub organization: &'a str,
    pub country: &'a str,
    pub state: &'a str,
    pub locality: &'a str,
    pub email: &'a str,
    pub key_algorithm: KeyAlgorithm,
    pub subject_alt_names: &'a [&'a str],
}

/// Both PEM outputs, mirroring `CSRResult`.
#[derive(Debug)]
pub struct CsrResult {
    pub csr: String,
    pub private_key: String,
}

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

/// DER length: short form below 0x80, long form (0x80 | byte count) above.
pub fn encode_length(len: usize) -> Vec<u8> {
    if len < 0x80 {
        return vec![len as u8];
    }
    let be = len.to_be_bytes();
    let first = be.iter().position(|&b| b != 0).expect("len >= 0x80 has a nonzero byte");
    let mut out = vec![0x80 | (be.len() - first) as u8];
    out.extend_from_slice(&be[first..]);
    out
}

/// Wrap content bytes in a tag + DER length header (TLV).
fn tlv(tag: u8, content: &[u8]) -> Vec<u8> {
    let mut out = vec![tag];
    out.extend_from_slice(&encode_length(content.len()));
    out.extend_from_slice(content);
    out
}

/// DER INTEGER from a small non-negative number (the CRI version, 0).
pub fn encode_integer(value: u64) -> Vec<u8> {
    let be = value.to_be_bytes();
    let first = be.iter().position(|&b| b != 0).unwrap_or(be.len() - 1); // 0 → one 0x00
    encode_integer_bytes(&be[first..])
}

/// DER INTEGER from raw big-endian bytes (signature r/s halves): leading zeros
/// stripped, a 0x00 sign byte prepended when the high bit is set (DER minimal).
pub fn encode_integer_bytes(raw: &[u8]) -> Vec<u8> {
    let mut body = raw;
    while body.len() > 1 && body[0] == 0 {
        body = &body[1..];
    }
    if body[0] > 0x7f {
        return tlv(0x02, &[&[0], body].concat());
    }
    tlv(0x02, body)
}

/// DER OBJECT IDENTIFIER from a dotted string, e.g. "1.2.840.113549.1.1.11".
pub fn encode_oid(oid: &str) -> Result<Vec<u8>, String> {
    let err = || format!("Invalid OID: {oid}");
    let parts: Vec<u64> = oid.split('.').map(|p| p.parse().map_err(|_| err())).collect::<Result<_, _>>()?;
    if parts.len() < 2 {
        return Err(err());
    }
    let mut content = vec![(40 * parts[0] + parts[1]) as u8];
    for &arc in &parts[2..] {
        let mut septets = vec![(arc & 0x7f) as u8]; // base-128, most significant first
        let mut v = arc / 128;
        while v > 0 {
            septets.insert(0, (v & 0x7f) as u8);
            v /= 128;
        }
        for (i, s) in septets.iter().enumerate() {
            content.push(if i + 1 < septets.len() { s | 0x80 } else { *s });
        }
    }
    Ok(tlv(0x06, &content))
}

/// UTF8String — every subject value except the country.
pub fn encode_utf8_string(s: &str) -> Vec<u8> {
    tlv(0x0c, s.as_bytes())
}

/// PrintableString — the required type for countryName in a Name.
pub fn encode_printable_string(s: &str) -> Result<Vec<u8>, String> {
    if !s.bytes().all(|b| b.is_ascii_alphanumeric() || b" '()+,-./:=?".contains(&b)) {
        return Err(format!("Not a PrintableString: {s}"));
    }
    Ok(tlv(0x13, s.as_bytes()))
}

/// BIT STRING with zero unused bits (signatures) / OCTET STRING (extension
/// values) / ASN.1 NULL / SEQUENCE and SET (the constructed workhorses).
pub fn encode_bit_string(data: &[u8]) -> Vec<u8> {
    tlv(0x03, &[&[0], data].concat())
}
pub fn encode_octet_string(data: &[u8]) -> Vec<u8> {
    tlv(0x04, data)
}
pub fn encode_null() -> Vec<u8> {
    vec![0x05, 0x00]
}
pub fn encode_sequence(parts: &[&[u8]]) -> Vec<u8> {
    tlv(0x30, &parts.concat())
}
pub fn encode_set(parts: &[&[u8]]) -> Vec<u8> {
    tlv(0x31, &parts.concat())
}

/// AttributeTypeAndValue (SEQUENCE of OID + value) wrapped in its RDN SET.
fn rdn(oid: &str, value: &[u8]) -> Result<Vec<u8>, String> {
    Ok(encode_set(&[&encode_sequence(&[&encode_oid(oid)?, value])]))
}

// --- Object identifiers ---------------------------------------------------------

const OID_COUNTRY: &str = "2.5.4.6";
const OID_STATE: &str = "2.5.4.8";
const OID_LOCALITY: &str = "2.5.4.7";
const OID_ORGANIZATION: &str = "2.5.4.10";
const OID_COMMON_NAME: &str = "2.5.4.3";
const OID_EMAIL: &str = "1.2.840.113549.1.9.1";
const OID_EXT_REQUEST: &str = "1.2.840.113549.1.9.14"; // pkcs-9 at extensionRequest
const OID_SUBJECT_ALT_NAME: &str = "2.5.29.17";
const OID_RSA_SHA256: &str = "1.2.840.113549.1.1.11"; // sha256WithRSAEncryption
const OID_ECDSA_SHA256: &str = "1.2.840.10045.4.3.2"; // ecdsa-with-SHA256

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

/// CN required; country (when present) a 2-letter ISO 3166-1 code. The key
/// algorithm needs no runtime check — the enum carries it.
pub fn validate_csr_options(o: &CsrOptions) -> Result<(), String> {
    if o.common_name.trim().is_empty() {
        return Err("Common Name (CN) is required".into());
    }
    let country = o.country.trim();
    if !country.is_empty() && (country.len() != 2 || !country.bytes().all(|b| b.is_ascii_alphabetic())) {
        return Err("Country must be a 2-letter ISO 3166-1 code (e.g. US, DE)".into());
    }
    Ok(())
}

// --- Subject alternative names ------------------------------------------------------

/// Packed 4- or 16-byte address bytes, or None when not an IP literal. Std's
/// `IpAddr::parse` covers dotted quads and IPv6 `::` shorthand — the role the
/// TS port's hand-rolled `ipToBytes` plays.
fn ip_to_bytes(ip: &str) -> Option<Vec<u8>> {
    match ip.parse::<std::net::IpAddr>() {
        Ok(std::net::IpAddr::V4(v4)) => Some(v4.octets().to_vec()),
        Ok(std::net::IpAddr::V6(v6)) => Some(v6.octets().to_vec()),
        Err(_) => None,
    }
}

/// Classify a SAN entry: IPv4/IPv6 → ip, http(s):// → uri, contains @ → email, else dns.
pub fn classify_san_type(entry: &str) -> &'static str {
    let value = entry.trim().to_lowercase();
    if ip_to_bytes(&value).is_some() {
        "ip"
    } else if value.starts_with("http://") || value.starts_with("https://") {
        "uri"
    } else if value.contains('@') {
        "email"
    } else {
        "dns"
    }
}

/// One GeneralName: context-specific implicit tags per RFC 5280.
fn encode_general_name(entry: &str) -> Vec<u8> {
    let value = entry.trim();
    match classify_san_type(value) {
        "ip" => tlv(0x87, &ip_to_bytes(&value.to_lowercase()).expect("classified as ip")),
        "uri" => tlv(0x86, value.as_bytes()),
        "email" => tlv(0x81, value.as_bytes()),
        _ => tlv(0x82, value.as_bytes()), // dNSName
    }
}

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

/// PEM-wrap DER bytes: 64-character base64 lines between BEGIN/END markers.
pub fn pem_encode(der: &[u8], label: &str) -> String {
    const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let mut b64 = String::with_capacity((der.len() + 2) / 3 * 4);
    for chunk in der.chunks(3) {
        let n = ((chunk[0] as u32) << 16) | ((*chunk.get(1).unwrap_or(&0) as u32) << 8) | (*chunk.get(2).unwrap_or(&0) as u32);
        for (shift, pad) in [(18, false), (12, chunk.len() < 2), (6, chunk.len() < 3), (0, chunk.len() < 3)] {
            b64.push(if pad { '=' } else { B64[((n >> shift) & 0x3f) as usize] as char });
        }
    }
    let lines: Vec<&str> = b64.as_bytes().chunks(64).map(|c| std::str::from_utf8(c).unwrap()).collect();
    format!("-----BEGIN {label}-----\n{}\n-----END {label}-----\n", lines.join("\n"))
}

/// Web Crypto ECDSA signatures are raw r||s; PKCS#10 expects a DER
/// ECDSA-Sig-Value SEQUENCE. Convert the half-length integer halves to DER.
pub fn ecdsa_raw_to_der(raw: &[u8]) -> Vec<u8> {
    let half = raw.len() / 2;
    encode_sequence(&[&encode_integer_bytes(&raw[..half]), &encode_integer_bytes(&raw[half..])])
}

// --- CSR assembly ----------------------------------------------------------------

/// Build a signed PKCS#10 CSR (PEM) plus the matching PKCS#8 private key (PEM).
/// The crypto-provider half of the TS `generateCSR` — keygen and signing — has
/// no std equivalent, so it is injected: `spki`/`pkcs8` are the raw DER exports
/// of an existing key; `sign` signs the DER CRI, returning raw r||s bytes for
/// ECDSA-P256 (converted here, as in the TS lib) or an RSASSA-PKCS1-v1_5
/// signature for RSA.
pub fn generate_csr(
    options: &CsrOptions,
    spki: &[u8],
    pkcs8: &[u8],
    sign: &dyn Fn(&[u8]) -> Result<Vec<u8>, String>,
) -> Result<CsrResult, String> {
    validate_csr_options(options)?;
    // subject: RDNSequence in the conventional C, ST, L, O, CN, email order
    let mut rdns: Vec<Vec<u8>> = Vec::new();
    let country = options.country.trim().to_uppercase();
    if !country.is_empty() {
        rdns.push(rdn(OID_COUNTRY, &encode_printable_string(&country)?)?);
    }
    for (field, oid) in [
        (&options.state, OID_STATE),
        (&options.locality, OID_LOCALITY),
        (&options.organization, OID_ORGANIZATION),
    ] {
        let value = field.trim();
        if !value.is_empty() {
            rdns.push(rdn(oid, &encode_utf8_string(value))?);
        }
    }
    rdns.push(rdn(OID_COMMON_NAME, &encode_utf8_string(options.common_name.trim()))?);
    let email = options.email.trim();
    if !email.is_empty() {
        rdns.push(rdn(OID_EMAIL, &encode_utf8_string(email))?);
    }
    // attributes [0] IMPLICIT SET OF — extensionRequest carrying subjectAltName
    let sans: Vec<&str> = options.subject_alt_names.iter().map(|s| s.trim()).filter(|s| !s.is_empty()).collect();
    let attributes = if sans.is_empty() {
        Vec::new()
    } else {
        let names: Vec<Vec<u8>> = sans.iter().map(|s| encode_general_name(s)).collect();
        let names: Vec<&[u8]> = names.iter().map(|g| g.as_slice()).collect();
        let extension = encode_sequence(&[&encode_oid(OID_SUBJECT_ALT_NAME)?, &encode_octet_string(&encode_sequence(&names))]);
        // Attribute = SEQUENCE { OID_extRequest, SET { SEQUENCE { extension } } }
        tlv(0xa0, &encode_sequence(&[&encode_oid(OID_EXT_REQUEST)?, &encode_set(&[&encode_sequence(&[&extension])])]))
    };
    // CertificationRequestInfo: version 0, subject, SPKI, [0] attributes
    let rdns: Vec<&[u8]> = rdns.iter().map(|r| r.as_slice()).collect();
    let cri = encode_sequence(&[&encode_integer(0), &encode_sequence(&rdns), spki, &attributes]);
    // signatureAlgorithm + signature over the DER CRI
    let (algorithm, signature) = match options.key_algorithm {
        KeyAlgorithm::EcdsaP256 => (
            encode_sequence(&[&encode_oid(OID_ECDSA_SHA256)?]),
            encode_bit_string(&ecdsa_raw_to_der(&sign(&cri)?)),
        ),
        KeyAlgorithm::Rsa2048 | KeyAlgorithm::Rsa4096 => (
            encode_sequence(&[&encode_oid(OID_RSA_SHA256)?, &encode_null()]),
            encode_bit_string(&sign(&cri)?),
        ),
    };
    Ok(CsrResult {
        csr: pem_encode(&encode_sequence(&[&cri, &algorithm, &signature]), "CERTIFICATE REQUEST"),
        private_key: pem_encode(pkcs8, "PRIVATE KEY"),
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn der_primitives_match_known_encodings() {
        assert_eq!(encode_length(5), [5]);
        assert_eq!(encode_length(300), [0x82, 1, 44]);
        assert_eq!(encode_integer(0), [0x02, 0x01, 0x00]);
        assert_eq!(encode_integer(0x80), [0x02, 0x02, 0x00, 0x80]);
        assert_eq!(encode_integer_bytes(&[0xff, 0x01]), [0x02, 0x03, 0x00, 0xff, 0x01]);
        assert_eq!(encode_oid(OID_RSA_SHA256).unwrap(), [0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b]);
        assert!(encode_oid("1").is_err());
        assert_eq!(encode_printable_string("US").unwrap(), [0x13, 0x02, b'U', b'S']);
        assert!(encode_printable_string("ÜS").is_err());
    }

    #[test]
    fn san_classification_and_helpers() {
        assert_eq!(classify_san_type(" 10.0.0.1 "), "ip");
        assert_eq!(classify_san_type("::ffff:10.0.0.1"), "ip");
        assert_eq!(classify_san_type("https://x.dev"), "uri");
        assert_eq!(classify_san_type("a@b.c"), "email");
        assert_eq!(classify_san_type("example.com"), "dns");
        assert_eq!(encode_general_name("10.0.0.1"), [0x87, 0x04, 10, 0, 0, 1]);
        assert_eq!(ecdsa_raw_to_der(&[0x81; 2]), encode_sequence(&[&encode_integer_bytes(&[0x81]), &encode_integer_bytes(&[0x81])]));
        assert!(pem_encode(&[1; 64], "TEST").starts_with("-----BEGIN TEST-----\n"));
    }

    #[test]
    fn full_csr_structure() {
        let result = generate_csr(
            &CsrOptions { common_name: "example.com", country: "us", subject_alt_names: &["example.com", "10.0.0.1"], ..Default::default() },
            &[0x30, 0x00],           // placeholder SPKI
            &[0x30, 0x00],           // placeholder PKCS#8
            &|msg| Ok(msg.to_vec()), // identity signer: signature = CRI bytes
        )
        .unwrap();
        assert!(result.csr.starts_with("-----BEGIN CERTIFICATE REQUEST-----\n"));
        assert!(result.private_key.starts_with("-----BEGIN PRIVATE KEY-----\n"));
        assert_eq!(generate_csr(&CsrOptions::default(), &[], &[], &|_| Ok(vec![])).unwrap_err(), "Common Name (CN) is required");
        assert!(generate_csr(&CsrOptions { common_name: "x", country: "USA", ..Default::default() }, &[], &[], &|_| Ok(vec![])).is_err());
    }
}

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 →