【问题标题】:Can PHP OpenSSL generate private/public key/certificate pairs?PHP OpenSSL 可以生成私钥/公钥/证书对吗?
【发布时间】:2024-10-04 07:00:01
【问题描述】:

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

【问题讨论】:

    标签: php openssl public-key-encryption


    【解决方案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);
    

    查看文档:

    【讨论】:

    • 你能解释一下 myNewPrivateKey.key 文件的存储位置吗???
    【解决方案2】:

    当然,使用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 导出密钥。

    【讨论】:

    • 感谢您的信息。这个页面的一个问题:php.net/manual/en/openssl.installation.php 说:“此外,如果您打算使用密钥生成和证书签名功能,您将需要在您的系统上安装一个有效的 openssl.cnf 文件。”。你有没有遇到过与 openssl.cnf 相关的问题?我有可能在共享主机上有一些吗?
    • @jayarjo 本段仅在 Windows 上运行 php 时相关,共享主机根本不可能运行 Windows,因此您应该清楚。如果它适用于您的系统,但不适用于您的主机,我建议您联系您的主机,并给他们一个在他们的机器上失败的简短示例程序。