如何从PHP OpenSSL库中的现有RSA公钥获取Modulus和Exponent

时间:2012-07-27 03:41:32

标签: php openssl rsa

有私钥,公钥,x509 Pem文件。 我想从这些文件中获取有关RSA公钥的信息。

我可以通过shell脚本确认如下。 $ openssl x509 -in cert.pem -text

...

    Subject Public Key Info:
        Public Key Algorithm: rsaEncryption
        RSA Public Key: (2048 bit)
            Modulus (2048 bit):
                00:e1:92:dc:05:84:c7:e1:2d:db:f3:48:84:90:32:
                ...
                da:7d:2f:95:d2:ab:28:6e:6c:be:0a:af:e0:cb:24:
                18:db
            Exponent: 65537 (0x10001)

...

我可以用同样的方式在PHP OpenSSL库中获取Modulus和Exponent的值吗?

3 个答案:

答案 0 :(得分:3)

您可以尝试以下操作:

$key = file_get_contents("root/to/private_key.pem");
$data = openssl_pkey_get_private($key);
$data = openssl_pkey_get_details($data);

$key = $data['key'];
$modulus = $data['rsa']['n'];
$exponent = $data['rsa']['e'];

echo "Modulus: $modulus <br>Exponent: $exponent";

如果 echoing $exponent在屏幕上没有显示任何内容,您可以尝试var_dump($exponent)var_dump($data),您会看到一些奇怪的字符。

答案 1 :(得分:1)

使用phpseclib, a pure PHP X.509 implementation

$x509 = new File_X509();
$cert = $x509->loadX509('-----BEGIN CERTIFICATE-----
MIIDITCCAoqgAwIBAgIQT52W2WawmStUwpV8tBV9TTANBgkqhkiG9w0BAQUFADBM
MQswCQYDVQQGEwJaQTElMCMGA1UEChMcVGhhd3RlIENvbnN1bHRpbmcgKFB0eSkg
THRkLjEWMBQGA1UEAxMNVGhhd3RlIFNHQyBDQTAeFw0xMTEwMjYwMDAwMDBaFw0x
MzA5MzAyMzU5NTlaMGgxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlh
MRYwFAYDVQQHFA1Nb3VudGFpbiBWaWV3MRMwEQYDVQQKFApHb29nbGUgSW5jMRcw
FQYDVQQDFA53d3cuZ29vZ2xlLmNvbTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkC
gYEA3rcmQ6aZhc04pxUJuc8PycNVjIjujI0oJyRLKl6g2Bb6YRhLz21ggNM1QDJy
wI8S2OVOj7my9tkVXlqGMaO6hqpryNlxjMzNJxMenUJdOPanrO/6YvMYgdQkRn8B
d3zGKokUmbuYOR2oGfs5AER9G5RqeC1prcB6LPrQ2iASmNMCAwEAAaOB5zCB5DAM
BgNVHRMBAf8EAjAAMDYGA1UdHwQvMC0wK6ApoCeGJWh0dHA6Ly9jcmwudGhhd3Rl
LmNvbS9UaGF3dGVTR0NDQS5jcmwwKAYDVR0lBCEwHwYIKwYBBQUHAwEGCCsGAQUF
BwMCBglghkgBhvhCBAEwcgYIKwYBBQUHAQEEZjBkMCIGCCsGAQUFBzABhhZodHRw
Oi8vb2NzcC50aGF3dGUuY29tMD4GCCsGAQUFBzAChjJodHRwOi8vd3d3LnRoYXd0
ZS5jb20vcmVwb3NpdG9yeS9UaGF3dGVfU0dDX0NBLmNydDANBgkqhkiG9w0BAQUF
AAOBgQAhrNWuyjSJWsKrUtKyNGadeqvu5nzVfsJcKLt0AMkQH0IT/GmKHiSgAgDp
ulvKGQSy068Bsn5fFNum21K5mvMSf3yinDtvmX3qUA12IxL/92ZzKbeVCq3Yi7Le
IOkKcGQRCMha8X2e7GmlpdWC1ycenlbN0nbVeSv3JUMcafC4+Q==
-----END CERTIFICATE-----');

$pubkey = $x509->getPublicKey();
$parts = $pubkey->getPublicKey(CRYPT_RSA_PUBLIC_FORMAT_RAW);
echo $parts['e'] . "\r\n\r\n" . $parts['n'];

答案 2 :(得分:0)

您可能想要openssl_pkey_get_details($key)

这需要从openssl_pkey_get_private()openssl_pkey_get_public()(?)生成关键资源,并返回包含密钥bitskeytype和第四个密钥是rsadsadh之一,具体取决于密钥。第四个键映射到另一个包含更多细节的数组;对于RSA密钥,此子数组包含模数n和指数e

有关更多使用说明,请参阅PHP文档中的this page及相关页面。

(这些都没有经过测试;请告诉我这是否适合您!)