CSR Generator — PHP 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 PHP implementation — the same logic the interactive tool runs, in a shareable, citable form.
<?php
/**
* csr-generator — ASN.1 DER encoding + PKCS#10 CSR construction.
*
* Language: PHP 7.4+ (bundled openssl extension + 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. PHP's stdlib has
* no key generation, so the bundled openssl extension (enabled by default) is
* used for exactly what the Ruby port uses OpenSSL for — key generation and
* the signature itself. Every DER byte of the CertificationRequest — length
* headers, INTEGER / OID / string primitives, the RDN sequence, the
* extensionRequest SAN attribute — is assembled by hand below, and the private
* key is hand-wrapped into PKCS#8 so the output matches the TS port's
* "BEGIN CERTIFICATE REQUEST" / "BEGIN PRIVATE KEY" pair byte-for-byte.
*
* One deliberate difference from the TS port: Web Crypto returns ECDSA
* signatures as raw r||s, so the TS code converts them to the DER
* ECDSA-Sig-Value PKCS#10 requires. openssl_sign already emits that DER
* SEQUENCE for EC keys, so no conversion step exists here.
*
* display source — part of CosmoDev's polyglot tool pages.
*/
declare(strict_types=1);
// --- DER primitives -----------------------------------------------------------
/** Minimal big-endian byte string for a positive integer (lengths + INTEGERs). */
function csrIntBytes(int $n): string
{
$out = '';
while ($n > 0) {
$out = chr($n & 0xff) . $out;
$n >>= 8;
}
return $out;
}
/** DER length: short form below 0x80, long form (0x80 | byte count) above. */
function encodeLength(int $len): string
{
if ($len < 0) {
throw new InvalidArgumentException('Length must be a non-negative integer');
}
if ($len < 0x80) {
return chr($len);
}
$bytes = csrIntBytes($len);
return chr(0x80 | strlen($bytes)) . $bytes;
}
/** Wrap content bytes in a tag + DER length header (TLV). */
function tlv(int $tag, string $content): string
{
return chr($tag) . encodeLength(strlen($content)) . $content;
}
/**
* DER INTEGER. Accepts a small non-negative int, or raw big-endian bytes (a
* signature / key half): leading zeros are stripped and a 0x00 sign byte is
* prepended when the high bit is set, per DER minimal-encoding rules.
*/
function encodeInteger($value): string
{
if (is_int($value)) {
if ($value < 0) {
throw new InvalidArgumentException('encodeInteger supports non-negative integers only');
}
$raw = csrIntBytes($value);
} else {
$raw = ltrim((string) $value, "\x00");
}
if ($raw === '') {
$raw = "\x00";
}
if (ord($raw[0]) > 0x7f) {
$raw = "\x00" . $raw;
}
return tlv(0x02, $raw);
}
/** DER OBJECT IDENTIFIER from a dotted string, e.g. '1.2.840.113549.1.1.11'. */
function encodeOid(string $oid): string
{
$parts = explode('.', $oid);
if (count($parts) < 2 || in_array('', $parts, true) || preg_grep('/[^0-9]/', $parts)) {
throw new InvalidArgumentException("Invalid OID: {$oid}");
}
$content = chr(40 * (int) $parts[0] + (int) $parts[1]);
foreach (array_slice($parts, 2) as $part) {
$septets = [];
for ($v = (int) $part; ; $v >>= 7) {
array_unshift($septets, $v & 0x7f);
if ($v < 128) {
break;
}
}
$last = count($septets) - 1;
foreach ($septets as $i => $septet) {
$content .= chr($i < $last ? $septet | 0x80 : $septet);
}
}
return tlv(0x06, $content);
}
function encodeUtf8String(string $str): string
{
return tlv(0x0c, $str); // PHP strings are byte buffers; UTF-8 in, UTF-8 out
}
/** PrintableString — the required type for countryName in a Name. */
function encodePrintableString(string $str): string
{
if (!preg_match('/^[A-Za-z0-9 \'()+,\-\/:=?]*$/', $str)) {
throw new InvalidArgumentException("Not a PrintableString: {$str}");
}
return tlv(0x13, $str);
}
function encodeBitString(string $data): string
{
return tlv(0x03, "\x00" . $data); // 0 unused bits in the last octet
}
function encodeOctetString(string $data): string
{
return tlv(0x04, $data);
}
function encodeNull(): string
{
return "\x05\x00";
}
function encodeSequence(string ...$parts): string
{
return tlv(0x30, implode('', $parts));
}
function encodeSet(string ...$parts): string
{
return tlv(0x31, implode('', $parts));
}
/** AttributeTypeAndValue (SEQUENCE of OID + value) wrapped in its RDN SET. */
function rdn(string $oid, string $value): string
{
return encodeSet(encodeSequence(encodeOid($oid), $value));
}
// --- Object identifiers ---------------------------------------------------------
const OID_COUNTRY = '2.5.4.6';
const OID_STATE = '2.5.4.8';
const OID_LOCALITY = '2.5.4.7';
const OID_ORGANIZATION = '2.5.4.10';
const OID_COMMON_NAME = '2.5.4.3';
const OID_EMAIL = '1.2.840.113549.1.9.1';
const OID_EXT_REQUEST = '1.2.840.113549.1.9.14'; // pkcs-9 at extensionRequest
const OID_SUBJECT_ALT_NAME = '2.5.29.17';
const OID_RSA_ENCRYPTION = '1.2.840.113549.1.1.1'; // rsaEncryption
const OID_RSA_SHA256 = '1.2.840.113549.1.1.11'; // sha256WithRSAEncryption
const OID_ECDSA_SHA256 = '1.2.840.10045.4.3.2'; // ecdsa-with-SHA256
const OID_EC_PUBLIC_KEY = '1.2.840.10045.2.1'; // id-ecPublicKey
const OID_PRIME256V1 = '1.2.840.10045.3.1.7'; // the P-256 curve itself
// --- Validation -------------------------------------------------------------------
/** Throws on invalid input: CN required, country (when present) a 2-letter ISO
* 3166-1 code, key algorithm one of the supported values. */
function validateCsrOptions(array $options): void
{
if (!isset($options['commonName']) || trim($options['commonName']) === '') {
throw new InvalidArgumentException('Common Name (CN) is required');
}
$country = isset($options['country']) ? trim($options['country']) : '';
if ($country !== '' && !preg_match('/^[A-Za-z]{2}$/', $country)) {
throw new InvalidArgumentException('Country must be a 2-letter ISO 3166-1 code (e.g. US, DE)');
}
if (!in_array($options['keyAlgorithm'] ?? '', ['RSA-2048', 'RSA-4096', 'ECDSA-P256'], true)) {
throw new InvalidArgumentException('Unsupported key algorithm: ' . strval($options['keyAlgorithm'] ?? ''));
}
}
// --- Subject alternative names ------------------------------------------------------
/** Classify a SAN entry: IPv4/IPv6 -> 'ip', http(s):// -> 'uri', contains an
* '@' -> 'email', everything else -> 'dns'. */
function classifySanType(string $entry): string
{
$value = strtolower(trim($entry));
if (ipToBytes($value) !== null) {
return 'ip';
}
if (preg_match('#^https?://#', $value)) {
return 'uri';
}
if (strpos($value, '@') !== false) {
return 'email';
}
return 'dns';
}
/** Packed 4- or 16-byte address, or null when the entry is not an IP literal.
* filter_var handles both dotted quad and IPv6 ('::' shorthand) validation. */
function ipToBytes(string $ip): ?string
{
if (filter_var($ip, FILTER_VALIDATE_IP) === false) {
return null;
}
return @inet_pton($ip) ?: null;
}
/** One GeneralName: context-specific implicit tags per RFC 5280. */
function encodeGeneralName(string $entry): string
{
$value = trim($entry);
switch (classifySanType($value)) {
case 'ip':
return tlv(0x87, (string) ipToBytes(strtolower($value)));
case 'uri':
return tlv(0x86, $value);
case 'email':
return tlv(0x81, $value);
default:
return tlv(0x82, $value); // dNSName
}
}
// --- PEM -------------------------------------------------------------------------
/** PEM-wrap DER bytes: 64-character base64 lines between BEGIN/END markers. */
function pemEncode(string $der, string $label): string
{
$lines = str_split(base64_encode($der), 64) ?: [];
return "-----BEGIN {$label}-----\n" . implode("\n", $lines) . "\n-----END {$label}-----\n";
}
// --- Key generation + CSR assembly ---------------------------------------------------
/** Generate the openssl key for an algorithm name: RSA-2048 / RSA-4096 / ECDSA-P256. */
function generateKeyPair(string $algorithm)
{
if ($algorithm === 'ECDSA-P256') {
return openssl_pkey_new(['private_key_type' => OPENSSL_KEYTYPE_EC, 'curve_name' => 'prime256v1']);
}
return openssl_pkey_new([
'private_key_type' => OPENSSL_KEYTYPE_RSA,
'private_key_bits' => $algorithm === 'RSA-4096' ? 4096 : 2048,
]);
}
/** SubjectPublicKeyInfo DER: openssl exports it as a "BEGIN PUBLIC KEY" PEM,
* so the wrapper is stripped and the base64 body decoded. */
function publicKeyDer($key): string
{
$pem = openssl_pkey_get_details($key)['key'];
$body = str_replace(['-----BEGIN PUBLIC KEY-----', '-----END PUBLIC KEY-----', "\r", "\n"], '', $pem);
return (string) base64_decode($body, true);
}
/** PKCS#8 PrivateKeyInfo hand-wrapped from openssl's key components, so the
* export is the same "BEGIN PRIVATE KEY" encoding WebCrypto's exportKey
* ('pkcs8') produces (openssl_pkey_export would give PKCS#1 / SEC1 wrappers). */
function privateKeyDer($key): string
{
$d = openssl_pkey_get_details($key);
if (($d['type'] ?? null) === OPENSSL_KEYTYPE_EC) {
$sec1 = encodeSequence(
encodeInteger(1),
encodeOctetString($d['ec']['d']),
tlv(0xa1, encodeBitString("\x04" . $d['ec']['x'] . $d['ec']['y'])) // [1] publicKey
);
$alg = encodeSequence(encodeOid(OID_EC_PUBLIC_KEY), encodeOid(OID_PRIME256V1));
} else {
// RSAPrivateKey = SEQUENCE { version, n, e, d, p, q, dp?, dq?, qinv? } —
// the CRT fields are OPTIONAL in PKCS#1, and newer PHP/OpenSSL builds no
// longer expose them via openssl_pkey_get_details, so they go in only
// when all three are present.
$ints = array_map(static function (string $f) use ($d): string {
return encodeInteger($d['rsa'][$f]);
}, ['n', 'e', 'd', 'p', 'q']);
$crt = ['dp', 'dq', 'qinv'];
if (isset($d['rsa']['dp'], $d['rsa']['dq'], $d['rsa']['qinv'])) {
$ints = array_merge($ints, array_map(static function (string $f) use ($d): string {
return encodeInteger($d['rsa'][$f]);
}, $crt));
}
$pkcs1 = encodeSequence(encodeInteger(0), ...$ints);
$alg = encodeSequence(encodeOid(OID_RSA_ENCRYPTION), encodeNull());
}
return encodeSequence(encodeInteger(0), $alg, encodeOctetString($sec1 ?? $pkcs1));
}
/** RDNSequence in the conventional C, ST, L, O, CN, email order. */
function subject(array $options): string
{
$rdns = [];
$country = strtoupper(trim($options['country'] ?? ''));
if ($country !== '') {
$rdns[] = rdn(OID_COUNTRY, encodePrintableString($country));
}
foreach ([['state', OID_STATE], ['locality', OID_LOCALITY], ['organization', OID_ORGANIZATION]] as [$field, $oid]) {
$value = trim($options[$field] ?? '');
if ($value !== '') {
$rdns[] = rdn($oid, encodeUtf8String($value));
}
}
$rdns[] = rdn(OID_COMMON_NAME, encodeUtf8String(trim($options['commonName'])));
$email = trim($options['email'] ?? '');
if ($email !== '') {
$rdns[] = rdn(OID_EMAIL, encodeUtf8String($email));
}
return encodeSequence(...$rdns);
}
/** [0] IMPLICIT SET OF Attribute — an extensionRequest carrying the
* subjectAltName extension; omitted when no SANs were requested. */
function attributes(array $options): string
{
$sans = [];
foreach ((array) ($options['subjectAltNames'] ?? []) as $san) {
$trimmed = trim((string) $san);
if ($trimmed !== '') {
$sans[] = $trimmed;
}
}
if ($sans === []) {
return '';
}
$extension = encodeSequence(
encodeOid(OID_SUBJECT_ALT_NAME),
encodeOctetString(encodeSequence(...array_map('encodeGeneralName', $sans)))
);
return tlv(0xa0, encodeSequence(encodeOid(OID_EXT_REQUEST), encodeSet(encodeSequence($extension))));
}
/**
* Generate a key pair and build a signed PKCS#10 CSR (PEM) plus the matching
* PKCS#8 private key (PEM). Same inputs produce the same DER structure as the
* TS lib; the key pair itself is freshly random on every call. Returns the
* CSRResult shape: ['csr' => string, 'privateKey' => string].
*/
function generateCsr(array $options): array
{
validateCsrOptions($options);
$key = generateKeyPair($options['keyAlgorithm']);
if ($key === false) {
throw new RuntimeException('Key generation failed');
}
$isEC = $options['keyAlgorithm'] === 'ECDSA-P256';
// CertificationRequestInfo: version 0, subject, SPKI, [0] attributes
$cri = encodeSequence(encodeInteger(0), subject($options), publicKeyDer($key), attributes($options));
// signatureAlgorithm + signature over the DER CRI (openssl_sign handles both
// RSASSA-PKCS1-v1_5 and ECDSA; EC signatures arrive as DER ECDSA-Sig-Value)
if ($isEC) {
$signatureAlgorithm = encodeSequence(encodeOid(OID_ECDSA_SHA256));
} else {
$signatureAlgorithm = encodeSequence(encodeOid(OID_RSA_SHA256), encodeNull());
}
openssl_sign($cri, $signature, $key, OPENSSL_ALGO_SHA256);
$csrDer = encodeSequence($cri, $signatureAlgorithm, encodeBitString($signature));
return [
'csr' => pemEncode($csrDer, 'CERTIFICATE REQUEST'),
'privateKey' => pemEncode(privateKeyDer($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 →