使用PHP生成RSA/ECC密钥对,可用于签发证书、微信/支付宝支付签名等。
<?php
$options = [
'private_key_bits' => 384,
'private_key_type' => OPENSSL_KEYTYPE_EC,
'curve_name' => 'secp384r1',
'config' => __DIR__ . '/openssl.cnf',
];
$private_key = openssl_pkey_new($options);
$keyDetail = openssl_pkey_get_details($private_key);
$publicKey = $keyDetail['key'];
$result = openssl_pkey_export($private_key, $privateKey, null, $options);
openssl_pkey_free($private_key);
echo json_encode(compact('privateKey', 'publicKey'), 256 | 128);
/*
{
"privateKey": "-----BEGIN EC PRIVATE KEY-----\nMIGkAgEBBDAmtrPgKoBN3pyuxqhbLerF7R1z34wM4+A6KZ9mVuILcRQMMg\/1R7al\nIBi1nloOsg6gBwYFK4EEACKhZANiAAQfI7zwMKkTd2mSdPDkOmLWlpi\/4rw30Kvw\n5k4G3Hv+gx6Nz6n1wKL7syRCvlG9JX2k+5UecsUfe1N6j+4QVQdF78pFp9paHIKg\n9opts2wcfM28sRmqcxn7o5JpqtXMc1Y=\n-----END EC PRIVATE KEY-----\n",
"publicKey": "-----BEGIN PUBLIC KEY-----\nMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEHyO88DCpE3dpknTw5Dpi1paYv+K8N9Cr\n8OZOBtx7\/oMejc+p9cCi+7MkQr5RvSV9pPuVHnLFH3tTeo\/uEFUHRe\/KRafaWhyC\noPaKbbNsHHzNvLEZqnMZ+6OSaarVzHNW\n-----END PUBLIC KEY-----\n"
}
*/
openssl.cnf
HOME = .
RANDFILE = $ENV::HOME/.rnd
生成ECC椭圆算法密钥对的options-两个推荐的曲线
//推荐最低384
$options = [
'private_key_bits' => 256,
'private_key_type' => OPENSSL_KEYTYPE_EC,
'curve_name' => 'prime256v1',
'config' => __DIR__ . '/openssl.cnf',
];
$options = [
'private_key_bits' => 384,
'private_key_type' => OPENSSL_KEYTYPE_EC,
'curve_name' => 'secp384r1',
'config' => __DIR__ . '/openssl.cnf',
];
RSA 参数
$options = [
'private_key_bits' => 2048 ,
'private_key_type' => OPENSSL_KEYTYPE_RSA ,
'config' => __DIR__ . '/openssl.cnf',
];