php生成公钥与私钥

FontSize: 【

 php生成公钥与私钥(该文章本来是自己看的,看到既然已经被搜索引擎收录了,就放出来吧,已忘记出处)。

// Generate a new RSA private key
$privateKey = openssl_pkey_new(array(
    'private_key_bits' => 2048,
    'private_key_type' => OPENSSL_KEYTYPE_RSA,
));

// Generate a new certificate signing request (CSR)
$csr = openssl_csr_new(array(
    'countryName' => 'CN',
    'organizationName' => 'Your Organization',
    'commonName' => 'Your Common Name',
), $privateKey);

// Generate a self-signed certificate valid for 365 days
$certificate = openssl_csr_sign($csr, null, $privateKey, 365);

// Save the private key to a file
openssl_pkey_export_to_file($privateKey, 'pri.key');

// Save the certificate to a file
openssl_x509_export_to_file($certificate, 'certificate.pem');

// Free up memory
openssl_pkey_free($privateKey);

报错:

openssl_csr_sign(): cannot get CSR from parameter 1

找到 openssl.cnf 调用的路径

使用phpinfo();找到openssl扩展,找到 Openssl default config 的路径,我这里是 C:Program FilesCommon FilesSSL/openssl.cnf,确认文件是否存在。

不存在的话,新建文件,输入以下内容,内容可以在这里获取,如果打不开,可以直接复制以下内容。

文件内容获取链接:https://github.com/openssl/openssl/blob/master/apps/openssl.cnf

可是,生成的证书无法正确解密。

用私钥创建公钥

/*用私钥创建公钥*/
// 读取私钥文件内容
$privateKeyContent = file_get_contents('pri.key');

// 载入私钥
$privateKey = openssl_pkey_get_private($privateKeyContent);

// 从私钥中提取公钥
$publicKey = openssl_pkey_get_details($privateKey)['key'];

// 保存公钥到文件
file_put_contents('pub.key', $publicKey);

// 释放资源
openssl_free_key($privateKey);

在这个示例中,我们首先使用file_get_contents()函数读取私钥文件的内容,并将内容存储在$privateKeyContent变量中。

然后,使用openssl_pkey_get_private()函数将私钥内容加载到一个私钥资源变量中。

接下来,使用openssl_pkey_get_details()函数从私钥资源中提取出公钥,并将公钥存储在$publicKey变量中。

最后,使用file_put_contents()函数将公钥保存到一个名为public_key.pem的文件中。

请确保使用正确的私钥文件路径和文件名,并根据您的实际需求进行相应的调整。

转载时请以链接形式注明原始出处及本声明。
微信扫一扫
SEO文章代写加微信
回到顶部