要使用PHP的openssl_pkey_new()函数创建SSL证书,您需要遵循以下步骤:
安装PHP OpenSSL扩展:确保已在您的服务器上安装并启用了PHP的OpenSSL扩展。这通常是默认启用的。您可以通过运行php -m | grep openssl来检查它是否已启用。
创建一个PHP脚本文件:创建一个新的PHP文件(例如:create_ssl_certificate.php),并在其中编写以下代码:
<?php// 生成私钥$privateKey = openssl_pkey_new(array( "private_key_bits" => 2048, // 密钥长度 "private_key_type" => OPENSSL_KEYTYPE_RSA, // 密钥类型));if (!$privateKey) { die("无法生成私钥");}// 生成公钥$publicKey = openssl_pkey_get_details($privateKey);$publicKey = $publicKey["key"];// 创建自签名证书$dn = array( "countryName" => "CN", "stateOrProvinceName" => "Beijing", "localityName" => "Beijing", "organizationName" => "My Organization", "organizationalUnitName" => "IT Department", "commonName" => "example.com", "emailAddress" => "admin@example.com");$csr = openssl_csr_new($dn, $privateKey);$sscert = openssl_csr_sign($csr, null, $privateKey, 365);// 将证书和私钥保存到文件openssl_x509_export_to_file($sscert, "certificate.crt");file_put_contents("private_key.pem", $privateKey);echo "SSL证书和私钥已创建!";?>运行脚本:在命令行中,导航到包含此PHP文件的目录,然后运行以下命令:php create_ssl_certificate.php获取证书和私钥:如果一切正常,您将在同一目录中看到两个新文件:certificate.crt(证书文件)和private_key.pem(私钥文件)。请注意,此示例创建的是自签名证书,因此在某些情况下可能不被信任。要获得受信任的证书,您需要向证书颁发机构(CA)提交证书签名请求(CSR)。


