PHP生成RSA/EC密钥对

更新于 2024-01-01

$options = [
    'private_key_bits' => 2048 ,
    'private_key_type' => OPENSSL_KEYTYPE_RSA ,
    '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'));

openssl.cnf

HOME            = .
RANDFILE        = $ENV::HOME/.rnd
生成EC椭圆算法密钥对的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',
];