【问题标题】:Convert openssl key to rsa public key in php在php中将openssl密钥转换为rsa公钥
【发布时间】:2017-10-03 15:07:33
【问题描述】:

有什么方法/什么是最好的方法来将 php 生成的 openssl 密钥转换为 rsa 公钥,我可以将它与 like 一起使用来加密我可以使用的数据用我的私钥加密。

谢谢

【问题讨论】:

    标签: php openssl


    【解决方案1】:

    根据this example,您可以在使用 openssl_pkey_new() 函数创建密钥时直接获取公钥:

    $config = array(
        "digest_alg" => "es256",
        "private_key_bits" => 4096,
        "private_key_type" => OPENSSL_KEYTYPE_RSA,
    );
    
    $res = openssl_pkey_new($config);
    openssl_pkey_export($res, $privKey, 'mypassphrase', $config);
    $pubKey = openssl_pkey_get_details($res);
    
    $pubKey = $pubKey["key"];
    var_dump($privKey, $pubKey);
    

    如果您直接拥有私钥,则可以使用openssl_pkey_get_private() 检索公钥:

    $privKey = file_get_contents('/path/to/private.pem');
    $res = openssl_pkey_get_private($privKey, 'mypassphrase');
    $pubKey = openssl_pkey_get_details($res);
    $pubKey = $pubKey["key"];
    var_dump($privKey, $pubKey);
    

    注意:如果 $res 为 false,您可能会收到 openssl_error_string 错误:

    $sslError = '';
    while ($msg = trim(openssl_error_string(), " \n\r\t\0\x0B\"")) {
        if (substr($msg, 0, 6) === 'error:') {
            $msg = substr($msg, 6);
        }
        $sslError .= "\n ".$msg;
    }
    

    【讨论】:

      猜你喜欢
      • 2015-10-19
      • 2011-07-28
      • 1970-01-01
      • 2020-07-05
      • 2014-11-27
      • 2011-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多