1 方法一 确保php环境已经开启了openssl模块:
$config = array(
"digest_alg" => "sha1",
"private_key_bits" => 1024,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
"config" => 'C:\phpstudy_pro\Extensions\Apache2.4.39\conf\openssl.cnf',
);
// 创建一个新的私钥和公钥对
$res = openssl_pkey_new($config);
// 检查是否成功生成密钥对
if ($res === false) {
die("无法生成密钥对:" . openssl_error_string());
}
// 提取私钥
openssl_pkey_export($res, $privateKey, NULL, $config); // <-- CONFIG ARRAY
// 生成公钥
$publicKey = openssl_pkey_get_details($res);
$publicKey = $publicKey["key"];
echo "私钥:" . $privateKey . "";
echo "公钥:" . $publicKey . "";
// 释放资源
openssl_free_key($res);2 方法二 使用openssl命令生成公钥和私钥:
1. 生成1024位RSA私钥
openssl genpkey -algorithm RSA -out private_key.pem -pkeyopt rsa\_keygen\_bits:1024
2. 从私钥中提取公钥
openssl rsa -pubout -in private_key.pem -out public\_key.pem
生成1024位的私钥,不指定的话默认2048位