配置证书参数
$dn = [ "countryName" => $organization['country'], // 国家代码 "stateOrProvinceName" => $organization['state'],// 省份名称 "localityName" => $organization['city'], // 城市名称 "commonName" => $this->domains[0], // 通用名称 (通常是域名) "emailAddress" => $organization['email']// 邮件地址 ]; $csr = CertHandling::generateSSLKeys($dn,$this->domains);
生成csr
public static function generateSSLKeys($dn, $domains = [],$passphrase = null)
{
// 生成配置选项
$config = [
"digest_alg" => "SHA256",
"private_key_bits" => 2048, // 生成 2048 位的私钥
"private_key_type" => OPENSSL_KEYTYPE_RSA, // 使用 RSA 算法
];
// 生成私钥
$privateKey = openssl_pkey_new($config);
if (!$privateKey) {
throw new BtException('Failed to generate private key: ' . openssl_error_string());
}
$publicKeyDetails = openssl_pkey_get_details($privateKey);
// 提取私钥并导出
openssl_pkey_export($privateKey, $privateKey, $passphrase);
$publicKey = $publicKeyDetails['key'];
// 处理 SAN(多个域名)
$sanConfig = "";
if (!empty($domains)) {
foreach ($domains as $index => $domain) {
$sanConfig .= "DNS.$index = $domain\n";
}
}
// 创建 OpenSSL 配置文件(支持 SAN)
$configFile = tempnam(sys_get_temp_dir(), 'openssl_');
file_put_contents($configFile, <<<EOL
[req]
distinguished_name = req_distinguished_name
req_extensions = v3_req
[req_distinguished_name]
[ v3_req ]
subjectAltName = @alt_names
[ alt_names ]
$sanConfig
EOL
);
//生成 CSR
$csr = openssl_csr_new($dn, $privateKey, ["config" => $configFile]);
unlink($configFile); // 删除临时文件
if (!$csr) {
throw new Exception('Failed to generate CSR: ' . openssl_error_string());
}
//导出 CSR
openssl_csr_export($csr, $csrOut);
// 返回私钥和 CSR
return [
"private_key" => $privateKey, // 私钥
"public_key" => $publicKey, // 公钥
'csr' => $csrOut,
];
}