简体   繁体   中英

Convert openssl key to rsa public key in php

is there any way / what is the best way to convert a in php generated openssl key, without direct shell use, into an rsa public key that i can use this together with something like this to encrypt data that i can encrypt with with my private key.

Thank you

According to this example , you can directy get the public key when you create the key with openssl_pkey_new() function :

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

If you have directly the private key, you can retrieve the public key with 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);

NB : If $res is false, you can get errors with 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM