I wonder if PHP's OpenSSL extension can be used to generate private/public key/certificate pairs?
Asked
Active
Viewed 1.5k times
2 Answers
14
Sure, use openssl_pkey_new
:
$privateKey = openssl_pkey_new(array('private_key_bits' => 2048));
$details = openssl_pkey_get_details($privateKey);
$publicKey = $details['key'];
You can export the keys with openssl_pkey_export
or openssl_pkey_export_to_file
.

phihag
- 278,196
- 72
- 453
- 469
-
Thanks for the info. One question this page here: http://www.php.net/manual/en/openssl.installation.php says that: "Additionally, if you are planning to use the key generation and certificate signing functions, you will need to install a valid openssl.cnf file on your system.". Have you ever had any openssl.cnf related problems? Is it possible I will have some on shared hosting? – jayarjo Sep 14 '11 at 10:10
-
1@jayarjo This paragraph is only relevant when running php on Windows, and it's unlikely a shared hoster would run Windows at all, so you should be in the clear. If it works on your system, but does not on your hoster's, I'd advise you to contact your hoster, and give them a short example program that fails on their machine. – phihag Sep 14 '11 at 10:26
8
I really appreciate the answer from phihag but was still struggling.
Ultimately, this helped:
$privateKeyResource = openssl_pkey_new([
'private_key_bits' => 2048,
'private_key_type' => OPENSSL_KEYTYPE_RSA
]);
// Save the private key to a file. Never share this file with anyone. See https://serverfault.com/questions/9708/what-is-a-pem-file-and-how-does-it-differ-from-other-openssl-generated-key-file
openssl_pkey_export_to_file($privateKeyResource, '/path/to/myNewPrivateKey.key');
// Generate the public key for the private key
$privateKeyDetailsArray = openssl_pkey_get_details($privateKeyResource);
// Save the public key to another file. Make this file available to anyone (especially anyone who wants to send you encrypted data).
file_put_contents('/path/to/myNewPublicKey.key', $privateKeyDetailsArray['key']);
// Free the key from memory.
openssl_free_key($privateKeyResource);
See docs:

Ryan
- 22,332
- 31
- 176
- 357