从保存的私钥PHP生成公钥

时间:2015-03-26 10:42:35

标签: php openssl

我已经以这种格式在DB中保存了私钥,例如

-----BEGIN PRIVATE KEY-----
 MIICdgIBADA................CHGIdCtZEmTD7sbLUcFCYDbohnqaWf2d+2I
 EyC/Hg/tS4d+BQ==
 -----END PRIVATE KEY-----

我需要从中提取公钥。 openssl_pkey_get_details 需要资源,但如何从字符串创建资源?

我试过这个

$public_key = openssl_pkey_get_details(openssl_pkey_get_public($private));  

错误是 openssl_pkey_get_details()期望参数1是资源,布尔给定

编辑1:

我正在尝试@kbarborak的解决方案,但是$ pk_get是假的:

$pk_string = "-----BEGIN PRIVATE KEY-----\n".chunk_split($data[4], 64, "\n")."-----END PRIVATE KEY-----\n";
$pk_get = openssl_pkey_get_private($pk_string);

die(var_dump($pk_string));

var_dump的输出是:

string(944) "-----BEGIN PRIVATE KEY-----
MIICjAIBAAINBgkqhkiG9w0BAQEFAAIJKoZIhvcNAQEBAgACggJhMIICXQIBAAKB
gQCvUSrEHS1T5g5z/Yv5ETeXA6CLsdo15Dqk0LevSAXGgbFarSRLfTYtN1/zwqgs
+YWnU/0lZKmzJpmDFRmH/wDeu8o7ptEOrNLgbs6TM85cS4ZmRhJnrOG3G6oBMq5m
UCPw+r06HIuxwyS54/2vY/GGjXpxV59yNUhKh9H9V216YwIDAQABAoGARZAbO/2n
wqaCDZwJMiaWvCEATu2e+8s3SbZXbAFT6VQEn0ocIKfqGz7hn8MZH99SHPbCd1fd
zev+9XglzURtf0sHneq8zT8qT4KYYriRj6dwlyJ6xpf1lLrBqi+eifvZR3+i60Ql
YuBNEXhq/OuSAwV+qTCLYrchUE0jTtX3HWECQQDerLyy1hs2SxlXgLbf80BdIuxB
gqj7QGirYBY/tnPvyLBJWF8RLGjEdPUEaN2hUgkhq2+IQ6lRADKJBQX+1u33AkEA
yY4Hz0rFgjDXx1PLOlX3z6vAFNhtWagcsz+DNp0fwaD1jLVvWnAcAgjJWQ9GBRrC
OGctw6hN92tX19vuKIbr9QJBAIFR1oESIVmlwcD0ysBDOFUezBC7vkG0xVUKB8HW
x3wxlFf0T7ncjbfSqN13vYdL6mu4cZy0lueo8rBqz3GSBz8CQQCTibEzzzL20xQQ
p8jbAfTtgnaPi8G34HRpzbMZ9jg5v74e6u0BEZGe95mT5LdHo0fKi9SXJYs08tGR
hD84UVNFAkAgR+Z0ox6HbNMj5bBIvqEC25mAMnayFyezPZ+/B/IyHDYmQSO9FGsG
/YVA8prMnAZ/YEiCC/2kYA2Ds7GjdJipAgACAAIAAgA=
-----END PRIVATE KEY-----
"

2 个答案:

答案 0 :(得分:2)

提取公钥

// Private key as string
$pem_private_key = file_get_contents('mykey.pem');

$private_key = openssl_pkey_get_private($pem_private_key);

// Public key as PEM string
$pem_public_key = openssl_pkey_get_details($private_key)['key'];
// As PHP resource
$public_key = openssl_pkey_get_public($pem_public_key);

echo $pem_public_key;
echo $public_key;

准备私钥字符串

$pk_string = "-----BEGIN RSA PRIVATE KEY-----\n".chunk_split($data[4], 64, "\n")."-----END RSA PRIVATE KEY-----\n";
$pk_get = openssl_pkey_get_private($pk_string);

die(var_dump($pk_string));

使用BEGIN RSA 私钥而不是BEGIN PRIVATE KEY(同样适用于END)。

希望有帮助。

答案 1 :(得分:0)

如果出现错误,

openssl_pkey_get_public()会返回false。所以这很有可能发生,并且正在将false传递给openssl_pkey_get_details()。调试你$private变量。