PHP 8.4.1 Released!

openssl_pkey_new

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

openssl_pkey_newGénère une nouvelle clé privée

Description

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

openssl_pkey_new() génère une nouvelle clé privée. Comment obtenir le composant publique de la clé est démontré dans un exemple ci-dessous.

Note: Vous devez avoir un fichier openssl.cnf valide et installé pour que cette fonction opère correctement. Voir les notes se trouvant dans la section concernant l'installation pour plus d'informations.

Liste de paramètres

options

Vous pouvez calibrer la génération de la clé (comme le nombre de bits) en utilisant le paramètre options. Voir la fonction openssl_csr_new() pour plus de détails sur options.

Valeurs de retour

Retourne une instance de OpenSSLAsymmetricKey en cas de succès, false en cas d'erreur.

Historique

Version Description
8.0.0 En cas de succès, cette fonction retourne désormais une instance de OpenSSLAsymmetricKey ; auparavant, une ressource de type OpenSSL key était retournée.
7.1.0 L'option curve_name a été ajouté pour permettre la création de clés EC.

Exemples

Exemple #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, PHP_EOL;

$public_key = openssl_pkey_get_public($public_key_pem);
var_dump($public_key);

?>

Résultat de l'exemple ci-dessus est similaire à :

// Résultat avant PHP 8.0.0 ; notez que la fonction retourne une ressource
-----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)

// Résultat à partir de PHP 8.0.0 ; notez que la fonction retourne un objet
-----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) {
}
add a note

User Contributed Notes 7 notes

up
50
dirt at awoms dot com
11 years ago
Working example:

$config = array(
"digest_alg" => "sha512",
"private_key_bits" => 4096,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
);

// Create the private and public key
$res = openssl_pkey_new($config);

// Extract the private key from $res to $privKey
openssl_pkey_export($res, $privKey);

// Extract the public key from $res to $pubKey
$pubKey = openssl_pkey_get_details($res);
$pubKey = $pubKey["key"];

$data = 'plaintext data goes here';

// Encrypt the data to $encrypted using the public key
openssl_public_encrypt($data, $encrypted, $pubKey);

// Decrypt the data using the private key and store the results in $decrypted
openssl_private_decrypt($encrypted, $decrypted, $privKey);

echo $decrypted;
up
18
gomez dot alejandre at gmail dot com
5 years ago
Not forget the $configArgs for windows users :D, or the method throws a error with the primary key

//write your configurations :D
$configargs = array(
"config" => "C:/xampp/php/extras/openssl/openssl.cnf",
'private_key_bits'=> 2048,
'default_md' => "sha256",
);

// Create the keypair
$res=openssl_pkey_new($configargs);
// Get private key
openssl_pkey_export($res, $privKey,NULL,$configargs);

and it's for all methods ._ .

a full implementation example here.

https://gist.github.com/DuckHunter213/269a0efd17e709f7f1f177ae7da46ad1

this error take me 3 full days you'r welcome :)
up
13
scott at brynen dot com
9 years ago
If you try and generate a new key using openssl_pkey_new(), and need to specify the size of the key, the key MUST be type-bound to integer

// works
$keysize = 1024;
$ssl = openssl_pkey_new (array('private_key_bits' => $keysize));

// fails
$keysize = "1024";
$ssl = openssl_pkey_new (array('private_key_bits' => $keysize));

// works (force to int)
$keysize = "1024";
$ssl = openssl_pkey_new (array('private_key_bits' => (int)$keysize));
up
3
Andrew
2 years ago
It's not documented here but you can also create ECC keys from existing key parameters (e.g. from JWK):

<?php
$key
= openssl_pkey_new([
'ec' => [
'curve_name' => 'prime256v1',
'x' => $someXValue,
'y' => $someYValue,
'd' => $someDValue
]
]);
?>

You can just provide x/y if it's a public key, or you can just provide d if it's a private key.
up
5
Brad
16 years ago
It's easier than all that, if you just want the keys:

<?php
// 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"];
?>
up
0
Jan
5 years ago
In case this function returns false, then check your openssl.cnf and make sure that in the [req] section of this file the entry default_bits is not commented out.
up
-1
dodginess at yahoo dot com
7 years ago
If you're using openssl_pkey_new() in conjunction with openssl_csr_new() and want to change the CSR digest algorithm as well as specify a custom key size, the configuration override should be defined once and sent to both functions:

<?php
$config
= array(
'digest_alg' => 'sha1',
'private_key_bits' => 2048,
'private_key_type' => OPENSSL_KEYTYPE_RSA,
);

$privkey = openssl_pkey_new($config);

$csr = openssl_csr_new($dn, $privkey, $config);
?>

Although openssl_pkey_new() will accept the 'digest_alg' argument it won't use it, and setting the value has no effect unless you also set this value for openssl_csr_new(). The reason for this is that the $config array is acting as a drop-in replacement for the values found in the openssl.cnf file, so it must contain all of the override values that you need even if the function they're being sent to won't use them.

Also, if you change the 'digest_alg' to something like 'sha256' and still get an MD5 signed CSR check your openssl.cnf file to see whether the digest algorithm you want to use is actually supported.
To Top