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

在php中将openssl密钥转换为rsa公钥,php,openssl,Php,Openssl,有没有什么方法/最好的方法可以将php生成的openssl密钥(无需直接使用shell)转换为rsa公钥,我可以将其与一些东西一起使用,以加密我可以使用私钥加密的数据 谢谢根据,您可以在使用openssl_pkey_new()函数创建密钥时直接获取公钥: $config = array( "digest_alg" => "es256", "private_key_bits" => 4096, "private_key_type" => OPENSSL_K

有没有什么方法/最好的方法可以将php生成的openssl密钥(无需直接使用shell)转换为rsa公钥,我可以将其与一些东西一起使用,以加密我可以使用私钥加密的数据

谢谢

根据,您可以在使用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);
如果您直接拥有私钥,则可以通过以下方式检索公钥:

注意:如果$res为false,则可能会出现以下错误:

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