直接上代码看吧,没啥说的
/**
* 生成公钥私钥
*/
public static function createRsa($id) {
//生成密钥的配置文件,官网:https://www.php.net/manual/fr/function.openssl-csr-new.php
//https://www.php.net/manual/fr/function.openssl-pkey-new.php
$config = [
//摘要方法或散列签名 string
'digest_alg' => 'sha512',
//字节数 512 1024 2048 4096 等
'private_key_bits' => 4096,
//加密类型 int
'private_key_type' => OPENSSL_KEYTYPE_RSA,
//导出的密钥是否加密 bool
// 'encrypt_key' => true,
//加密的话,密码常量 int
// 'encrypt_key_cipher' => OPENSSL_CIPHER_AES_256_CBC ,
];
//创建密钥对
$res = openssl_pkey_new($config);
//生成私钥
openssl_pkey_export($res, $priKey);
//生成公钥
$pubKey = openssl_pkey_get_details($res)['key'];
$data = [
'public_key' => $pubKey,
'private_key' => $priKey,
];
file_put_contents('../secretkey/sxy_public_key_' . $id . '.pem', $pubKey);
file_put_contents('../secretkey/sxy_private_key_' . $id . '.pem', $priKey);
return $data;
}
/**
* 生成证书
*/
public static function Certificate() {
$dn = [
//所在国家
'countryName' => 'GB',
//所在省份
'stateOrProvinceName' => 'Somerset',
//所在城市
'localityName' => 'Glastonbury',
//注册人姓名
'organizationName' => 'The Brain Room Limited',
//组织名称
'organizationalUnitName' => 'PHP Documentation Team',
//公共名称
'commonName' => 'Wez Furlong',
//邮箱
'emailAddress' => 'wez@example.com'
];
$config = [
'digest_alg' => 'sha512',
'private_key_bits' => 2048,
'private_key_type' => OPENSSL_KEYTYPE_RSA,
];
//创建密钥对
$res = openssl_pkey_new($config);
//证书
$csr = openssl_csr_new($dn, $res);
//证书签名
$usercert = openssl_csr_sign($csr, null, $res, 365);
//导出证书公钥
openssl_x509_export_to_file($usercert, 'csr.public.cert');
//私钥密码
$privkeypass = '123456789';
//导出证书私钥
openssl_pkcs12_export_to_file($usercert, 'csr.private.pfx', $res, $privkeypass);
}