PHP OpenSSL可以生成私钥/公钥/证书对吗?

jay*_*rjo 5 php openssl public-key-encryption

我想知道PHP的OpenSSL扩展是否可用于生成私钥/公钥/证书对?

phi*_*hag 11

当然,使用openssl_pkey_new:

$privateKey = openssl_pkey_new(array('private_key_bits' => 2048));
$details = openssl_pkey_get_details($privateKey);
$publicKey = $details['key'];
Run Code Online (Sandbox Code Playgroud)

您可以使用openssl_pkey_export或导出密钥openssl_pkey_export_to_file.


Rya*_*yan 5

我真的很感谢 phihag 的回答,但仍在挣扎。

最终,有助于:

$privateKeyResource = openssl_pkey_new([
    'private_key_bits' => 2048,
    'private_key_type' => OPENSSL_KEYTYPE_RSA
]);

// Save the private key to a file. Never share this file with anyone. See https://serverfault.com/questions/9708/what-is-a-pem-file-and-how-does-it-differ-from-other-openssl-generated-key-file
openssl_pkey_export_to_file($privateKeyResource, '/path/to/myNewPrivateKey.key');

// Generate the public key for the private key
$privateKeyDetailsArray = openssl_pkey_get_details($privateKeyResource);

// Save the public key to another file. Make this file available to anyone (especially anyone who wants to send you encrypted data).
file_put_contents('/path/to/myNewPublicKey.key', $privateKeyDetailsArray['key']);

// Free the key from memory.
openssl_free_key($privateKeyResource);
Run Code Online (Sandbox Code Playgroud)

查看文档: