openssl_pkey_new

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

openssl_pkey_newGenerates a new private key

Description

openssl_pkey_new(?array $options = null): OpenSSLAsymmetricKey|false

openssl_pkey_new() generates a new private key. How to obtain the public component of the key is shown in an example below.

Note: You need to have a valid openssl.cnf installed for this function to operate correctly. See the notes under the installation section for more information.

Parameters

options

You can finetune the key generation (such as specifying the number of bits) using options. See openssl_csr_new() for more information about options.

Return Values

Returns an OpenSSLAsymmetricKey instance for the pkey on success, or false on error.

Changelog

Version Description
8.0.0 On success, this function returns an OpenSSLAsymmetricKey instance now; previously, a resource of type OpenSSL key was returned.
7.1.0 The curve_name option was added to make it possible to create EC keys.

Examples

Example #1 Obtain the public key from a private key

<?php
$private_key 
openssl_pkey_new();
$public_key_pem openssl_pkey_get_details($private_key)['key'];
echo 
$public_key_pem;
$public_key openssl_pkey_get_public($public_key_pem);
var_dump($public_key);
?>

The above example will output something similar to:

-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArZFsmN2P6rx1Xt7YV95o
gcdlal0k3ryiIhFNzjwtRNNTXfEfBr6lUuaIJYQ8/XqEBX0hpcfuuF6tTRlonA3t
WLME0QFD93YVsAaXcy76YqjjqcRRodIBphAbYyyMI/lXkQAdn7kbAmr7neSOsMYJ
El9Wo4Hl4oG6e52ZnYHyqW9dxh4hX93eupR2TmcCdVf+r9xoHewP0KJYSHt7vDUX
AQlWYcQiWHIadFsmL0orr6mutlXFReoHbesgKY9/3YLOu0JfxflSjIZ2JeL1NTl1
MsmODsUwgAUrwnWKKx+eQUP5g3GnSB3dPkRh9zRVRiLNWbCugyjrf3e6DgQWrW7j
pwIDAQAB
-----END PUBLIC KEY-----
resource(5) of type (OpenSSL key)