Skip to content

Instantly share code, notes, and snippets.

@dol
Last active August 13, 2020 08:20
Show Gist options
  • Save dol/e0b7f084e2e7158efc87 to your computer and use it in GitHub Desktop.
Save dol/e0b7f084e2e7158efc87 to your computer and use it in GitHub Desktop.
PHP CSR with subjectAltName
<?php
$keyConfig = [
'private_key_type' => OPENSSL_KEYTYPE_RSA,
'private_key_bits' => 2048,
];
$key = openssl_pkey_new($keyConfig);
$sanDomains = [
'mydomain.tld',
'seconddomain.tld',
];
$dn = [
'commonName' => reset($sanDomains),
];
$csrConfig = [
'config' => __DIR__ . '/openssl.cnf',
'req_extensions' => 'v3_req',
'digest_alg' => 'sha256',
];
$addPrefix = function ($value) {
// Important: Sanatize domain value and check if a valid domain
return 'DNS:' . $value;
};
$sanDomainPrefixed = array_map($addPrefix, $sanDomains);
putenv('PHP_PASS_SUBJECTALTNAME=' . implode(',', $sanDomainPrefixed));
$csr = openssl_csr_new($dn, $key, $csrConfig);
if (false === $csr) {
while (($e = openssl_error_string()) !== false) {
echo $e . '\n';
}
return;
}
openssl_csr_export($csr, $csrout);
echo $csrout;
[ req ]
distinguished_name = req_distinguished_name
req_extensions = v3_req
[ req_distinguished_name ]
[ v3_req ]
basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment
subjectAltName = ${ENV::PHP_PASS_SUBJECTALTNAME}
@vreemt
Copy link

vreemt commented Feb 28, 2020

Please help me ... I generated a san csr using . But how can I get subjectaltname using php

try

$out = openssl_x509_parse($csrout);
var_dump($out);

I basically copied the script above, but added some comments - see also https://gist.github.com/vreemt/7070fced19b0eddbce75edfc5cbf958e

@dol
Copy link
Author

dol commented Mar 2, 2020

@thestorm-star openssl_x509_parse doesn't support parsing a CSR. Please take my https://gist.github.com/dol/e9f3d682529ae7ee368f0e6862e16a87 example that shows how to do this with an X501 parser library.

@thestorm-star
Copy link

thestorm-star commented Aug 12, 2020 via email

@dol
Copy link
Author

dol commented Aug 13, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment