Friday, October 10, 2025
HomeLanguagesPHP openssl_pkey_new() Function

PHP openssl_pkey_new() Function

The openssl_pkey_new() function is an inbuilt function in PHP cryptography extension that is used to generate a new private/public key pair using the OpenSSL library.

Syntax:

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

Parameters: This function accepts one parameter which is described below.

  • $options: An optional array of configuration options that can be used to customize the key generation process. This can include options such as the key type, key length, and digest algorithm.

Return Values: The return value of openssl_pkey_new() is a new OpenSSL key pair resource that can be used with other OpenSSL functions. This resource represents both the private and public key components of the generated key pair. If it fails, it will return false.

Example 1: The following program demonstrates the openssl_pkey_new() function.

PHP




<?php
$config = [
    "private_key_bits" => 2048,
    "private_key_type" => OPENSSL_KEYTYPE_RSA,
];
  
$keypair = openssl_pkey_new($config);
  
openssl_pkey_export($keypair, $private_key);
  
$public_key = openssl_pkey_get_details($keypair);
$public_key = $public_key["key"];
  
echo "Private key: " . $private_key . "\n";
echo "Public key: " . $public_key . "\n";
?>


Output:

Private key: -----BEGIN PRIVATE KEY-----
MIIEvAIBADANBgkqhkiG9w0...
...
...o9NsYUeNhM2eTDd5KnyQA==
-----END PRIVATE KEY-----
Public key: -----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQE...
...
...JmQQIDAQABDGSFdgKHJhgER
-----END PUBLIC KEY-----

Example 2: The following program demonstrates the openssl_pkey_new() function.

PHP




<?php
$config = [
    "private_key_bits" => 2048,
    "private_key_type" => OPENSSL_KEYTYPE_RSA,
];
  
$keypair = openssl_pkey_new($config);
  
if ($keypair) {
    openssl_pkey_export($keypair, $private_key);
    if ($private_key) {
        echo "Private key successfully exported\n";
    } else {
        echo "Error exporting private key\n";
    }
} else {
    echo "Error generating key pair\n";
}
?>


Output:

Private key successfully exported

Reference: https://www.php.net/manual/en/function.openssl-pkey-new.php

RELATED ARTICLES

Most Popular

Dominic
32350 POSTS0 COMMENTS
Milvus
87 POSTS0 COMMENTS
Nango Kala
6718 POSTS0 COMMENTS
Nicole Veronica
11880 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11941 POSTS0 COMMENTS
Shaida Kate Naidoo
6838 POSTS0 COMMENTS
Ted Musemwa
7101 POSTS0 COMMENTS
Thapelo Manthata
6794 POSTS0 COMMENTS
Umr Jansen
6794 POSTS0 COMMENTS