2

I am getting the error Warning: openssl_get_publickey() [function.openssl-get-publickey]: Don't know how to get public key from this private key on line 5 When trying to get a public key from a private key. Here is my PHP code:

<?php
$privatekeyorig = openssl_pkey_new();
openssl_pkey_export($privatekeyorig,$privatekey);
echo '<b>Private Key:</b> ' . $privatekey . '<br>';
$publickey = openssl_get_publickey($privatekeyorig);
echo '<b>Public Key:</b> ' . $publickey . '<br>';
?>

According to the PHP manual I am doing this correctly. Anyone spot an error? Help would be greatly appreciated!

2 Answers 2

2

My recommendation would be to use phpseclib, a pure PHP RSA implementation. eg.

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

$rsa = new Crypt_RSA();
$rsa->loadKey('...');

$privatekey = $rsa->getPrivateKey();
$publickey = $rsa->getPublicKey();
?>
Sign up to request clarification or add additional context in comments.

2 Comments

Unfortunately I can't install anything on my host and since OpenSSL is already installed I thought it might work. I also can't use mcrypt as I need asymmetrical encryption.
You don't need to install anything. Just upload the PHP files and you're done. That's the whole point of phpseclib. The developer went to great pains to make sure that not even bcmath or gmp were required. They're used if they're available, for speed, but aren't required.
1

Check out the last comment on http://php.net/manual/en/function.openssl-pkey-new.php

[UPDATE] From the comment right before the above :) and it works on my system to give you a textual public key:

// Create the keypair
$res=openssl_pkey_new();

// Get private key
openssl_pkey_export($res, $privkey);

// Get public key
$pubkey=openssl_pkey_get_details($res);
$pubkey=$pubkey["key"];

3 Comments

I already looked at that - it is exporting the key as a certificate I want it to be a plain text key, just like the private key I have generated.
@ethanh The comment prior to the last one is more useful then. I updated the answer.
Is there something wrong with this answer? I'm curious why it got down voted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.