使用openssl库在php中构建具有现有模数和指数的公钥PEM文件

时间:2013-03-31 15:09:48

标签: php encryption openssl rsa

我有公钥的模数和指数。我可以用php中的openssl api生成公钥吗?我已经阅读了http://php.net/manual/en/ref.openssl.php,但似乎没有归档的功能。

如果openssl不能这样做(使用模数和指数构建公钥),我可以使用php中的任何选项来做到这一点吗?

2 个答案:

答案 0 :(得分:1)

使用phpseclib, a pure PHP RSA implementation

<?php
include('Crypt/RSA.php');

$rsa = new Crypt_RSA();

$rsa->loadKey( array ('e'=>new Math_BigInteger('65537'), 'n'=>new Math_BigInteger('11944573237954459805614520005393273287786384679965238498958830373752732874397055'.
'98832111464872863171681422024469555089029360351247093972211786644957214280299847'.
'26868375359168203283442617134197706515425366188396513684446494070223079865755643'.
'116690165578452542158755074958452695530623055205290232290667934914919')) );

echo $rsa;

输出如下:

-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCqGKukO1De7zhZj6+H0qtjTkVx
wTCpvKe4eCZ0FPqri0cb2JZfXJ/DgYSF6vUpwmJG8wVQZKjeGcjDOL5UlsuusFnc
CzWBQ7RKNUSesmQRMSGkVb1/3j+skZ6UtW+5u09lHNsj6tQ51s1SPrCBkedbNf0T
p0GbMJDyR4e9T04ZZwIDAQAB
-----END PUBLIC KEY-----

答案 1 :(得分:0)

如果您的模数和指数来自XML格式的RSA密钥,或者您正在从JWKS端点检索密钥,则可以使用以下代码:

use phpseclib\Crypt\RSA;

$n = "6R-qAvAPQNrx8I_Q7GmQE4zpKFBpKMM38yeFE797v9eLBdXr9JIW5PBuBqjkmzMug3MUvl4FM6_nU0SCMLDMSY_zGIt5xlmFF5iqRb8elTZ_bLe6bp_1cZncadl4vzRdi6jQE_aIZX_9CWypO4su-kNj6DVCh5wldbGZej0c-1sKCgkJF12hiAqQPxaIA4hDgDCFiCRWSPzxHRuS-aXV0h3DIhn84lCkzrBqWea-nS03z0k2ohmuNsTd0yIPz_s-R2TkE-lUaKVtKGqsRPL3GKzQJO4TUzYmqHkN8XyNkmvBaitWreiZjyX79qTJ46SNX55gzVAfWqevpJc0RezVsQ==";
$e = "AQAB";

// Convert Base64 uri-safe variant to default (needed for JWKS)
$n = strtr($n, '-_', '+/');

$rsa = new RSA();

$key = "<RSAKeyPair>"
        . "<Modulus>" . $n . "</Modulus>"
        . "<Exponent>" . $e . "</Exponent>"
        . "</RSAKeyPair>";

$rsa->loadKey($key, RSA::PUBLIC_FORMAT_XML);

echo $rsa;