fr33m4n
fr33m4n

Reputation: 552

build public key PEM file with existing modulus and exponent in php with openssl library

I have public's key's modulus and exponent. Can I generate the public key with openssl api in php ? I've read the http://php.net/manual/en/ref.openssl.php but there seems no function that archive that.

If openssl cannot do it(build public key with modulus and exponent), can i use any any option in php to do that?

Upvotes: 0

Views: 4093

Answers (2)

xonya
xonya

Reputation: 2474

If your modulus and exponent came from a RSA key in XML format or you are retrieving the key from a JWKS endpoint you can use the following code:

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;

Upvotes: 1

neubert
neubert

Reputation: 16782

Using 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;

The output is as follows:

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

Upvotes: 2

Related Questions