在open中将openssl密钥转换为rsa公钥

时间:2017-10-03 15:07:33

标签: php openssl

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

谢谢

1 个答案:

答案 0 :(得分:2)

根据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;
}