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

发布于 2024-12-04 15:17:03 字数 119 浏览 1 评论 0 原文

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

I wonder if PHP's OpenSSL extension can be used to generate private/public key/certificate pairs?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

埋葬我深情 2024-12-11 15:17:03

当然,使用 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

Sure, use openssl_pkey_new:

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

You can export the keys with openssl_pkey_export or openssl_pkey_export_to_file.

倾城泪 2024-12-11 15:17:03

我真的很感谢 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);

请参阅文档:

I really appreciate the answer from phihag but was still struggling.

Ultimately, this helped:

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

See docs:

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文