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
It is possible to fine-tune the key generation (e.g. specifying the number of
bits or parameters) using the options parameter.
These options can either be algorithm-specific parameters used for key generation,
or generic options used also in CSRgeneration if not specified.
See openssl_csr_new() for more information
about how to use options for a CSR.
Among those options only private_key_bits,
private_key_type, curve_name,
and config are used for key generation.
Algorithm-specific options are used if the associative array includes one of the specific keys.
Added support for Curve25519 and Curve448 based keys with the introduction of the
x25519, ed25519, x448,
and ed448 fields.
8.3.0
Added support for generation EC keys with custom EC parameters.
Specifically with the introduction of the EC options:
p, a, b, seed,
generator, g_x, g_y,
cofactor, and order.
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 key of the options parameter was
added to make it possible to create EC keys based on Elliptic Curve algorithms.
Examples
Example #1 Obtain the public key from a private key
The above example will output
something similar to:
// Output prior to PHP 8.0.0; note, the function returns a resource
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwknBFEherZe74BiRjTFA
hqwZ1SK7brwq7C/afnLXKhRR7jnrpfM0ypC46q8xz5UZswenZakJ7kd5fls+r4Bv
3P8XsKYLTh2m1GiWQhV1g77cNIN4qNWh70PiDO3fB2446o1LBgToQYuRZS5YQRfJ
rVD0ysgtVcCU9tjaey28HlgApOpYFTaaKPj2MBmEYpMC+kG2HhL12GfpHUi2eiXI
dXT2WskWHWvUrmQ7fJIfI92JlDokV62DH/q1oiedLs9OPNb0rL1aAmYdzaVN6XNH
x/o4Lh125v2vAPV9E3fZCDc/HDEUaahpjanMiCQEgEDp5Hr+CRkvERT5/ydN+p08
5wIDAQAB
-----END PUBLIC KEY-----
resource(6) of type (OpenSSL key)
// Output as of PHP 8.0.0; note, the function returns an object
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwknBFEherZe74BiRjTFA
hqwZ1SK7brwq7C/afnLXKhRR7jnrpfM0ypC46q8xz5UZswenZakJ7kd5fls+r4Bv
3P8XsKYLTh2m1GiWQhV1g77cNIN4qNWh70PiDO3fB2446o1LBgToQYuRZS5YQRfJ
rVD0ysgtVcCU9tjaey28HlgApOpYFTaaKPj2MBmEYpMC+kG2HhL12GfpHUi2eiXI
dXT2WskWHWvUrmQ7fJIfI92JlDokV62DH/q1oiedLs9OPNb0rL1aAmYdzaVN6XNH
x/o4Lh125v2vAPV9E3fZCDc/HDEUaahpjanMiCQEgEDp5Hr+CRkvERT5/ydN+p08
5wIDAQAB
-----END PUBLIC KEY-----
object(OpenSSLAsymmetricKey)#2 (0) {
}