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

时间:2011-09-14 09:23:45

标签: php openssl public-key-encryption

我想知道是否可以使用PHP's OpenSSL扩展来生成私钥/公钥/证书对吗?

2 个答案:

答案 0 :(得分:10)

当然,请使用openssl_pkey_new

$privateKey = openssl_pkey_new(array('private_key_bits' => 2048));
$details = openssl_pkey_get_details($privateKey);
$publicKey = $details['key'];

您可以使用openssl_pkey_exportopenssl_pkey_export_to_file

导出密钥

答案 1 :(得分:1)

我真的很感谢phihag的回答,但仍在努力。

this最终帮助:

$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);

查看文档: