PHP | openssl_pkey_new() Function

PHP openssl_pkey_new() Function


Hello folks! welcome back to a new edition of our tutorial on PHP. In this tutorial guide, we are going to be studying about the PHP openssl_pkey_new() Function.

The openssl_pkey_new() function returns a resource identifier that has new private and public key pair.

This function returns a resource identifier. You can use openssl_pkey_get_details() function to get all the details of the key generated. The key (public/private pair) is used later with other openssl functions like openssl_sign(), openssl_csr_new() to get CSR certificate, that helps in the creation of cryptographic digital signature.

syntax

Following below is the syntax to use this function -

openssl_pkey_new ([ array $configargs ] ) : resource


Parameter Details

Sr.NoParameterDescription
1

configargs

The parameter configargs is the configuration details that need to be given to the function to generate the private/public key pair. The details are described below.


configargs

By default the openssl_pkey_new() function makes use of configuration details present in openssl.cnf. But using configargs you can overwrite them. The config details are as follows -

key in configargstypekey used in openssl.confdescription
digest_algstringdefault_mdDigest methods that you get from openssl_get_md_methods().
x509_extensionsstringx509_extensionsExtensions used when creating an x509 certificate.
req_extensionsstringreq_extensionsExtensions used when creating a CSR.
private_key_bitsintegerdefault_bitsSpecifies how many bits to be used while generating a private key.
private_key_typeintegernoneThe type of private key to create. It can be one of OPENSSL_KEYTYPE_DSA, OPENSSL_KEYTYPE_DH, OPENSSL_KEYTYPE_RSA or OPENSSL_KEYTYPE_EC. The default value is OPENSSL_KEYTYPE_RSA.
encrypt_keybooleanencrypt_keyWhether the exported key be encrypted?
encrypt_key_cipherintegernoneCipher constants like OPENSSL_CIPHER_RC2_40 (integer),OPENSSL_CIPHER_RC2_128 (integer),OPENSSL_CIPHER_RC2_64 (integer),OPENSSL_CIPHER_DES (integer), OPENSSL_CIPHER_3DES (integer) etc.
curve_namestringnoneOne of the curve name returned by this function openssl_get_curve_names().
configstringN/AYou can change the configuration in openssl.conf as per your requirement and give the path of it here.

Return Value

This function returns a resource identifier if there is no error, or it returns false if the key generation fails.

PHP Version

This built-in function works from PHP version greater than 5.0.0.

Example1

The following example below illustrates the usage of the openssl_pkey_new() function -

<?php
   // Generate a new private (and public) key pair
   $privkey = openssl_pkey_new(array(
      "digest_alg"=>'md5',
      "private_key_bits" => 2048,
      "private_key_type" => OPENSSL_KEYTYPE_RSA,
   ));
   var_dump($privkey);
?>

Output

When the above code is executed, it will produce the following result -

resource(2) of type (OpenSSL key)

Example2

The following example below illustrates the usage of the PHP openssl_pkey_new() and PHP openssl_pkey_get_details() functions -

<?php
   // Generate a new private (and public) key pair
   $privkey = openssl_pkey_new(array(
      "digest_alg"=>'md5',
      "private_key_bits" => 2048,
      "private_key_type" => OPENSSL_KEYTYPE_RSA,
   ));
   $key_details = openssl_pkey_get_details($privkey);
   print_r($key_details);
?>

Output

When the above code is executed, it will produce the following result -

Array (
   [bits] => 2048
   [key] => -----BEGIN PUBLIC KEY-----
   MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1IGWxnWzICSkjrOVrYkw
   9EKpIhcAYbhaymiwQY/ii9d7hnuGhpjjitDxzFftGafL6XOFKOhgbO2yrcpFxRKu
   AY3t5wyUcqUJV6CNwV2Hipk90psUcTmK3+pcCzcqCKr7sLWlHI48lse92xane8Sf
   CATNNbr9vmqUaTZ9FQqWihm3o/rNGuZTwMSKvcKsVguFpwrEDJaSLP1nt7RSHGc+
   PixQSXp3PtQCH+S0CM9jt1jD9NkYXuuAlNbrsPm1fl2zAGR5Vh15evz5765lZ2mH
   LIZScfsO/qgai3R6foaBlJM5tiSeiVZgnnQDKFBi5XK2GhzDnKggJe4tdY7awTFm
   CQIDAQAB
   -----END PUBLIC KEY-----

   [rsa] => Array (
      [n] => ԁ��u� $��0�B�"a�Z�h�A��{�{��W���s�(�`l��E�����r�	W��]��=қq9��\7*���<�ǽ��{ğ�5��j�i6}
      �����S�Ċ�¬V��
      ���,�g��Rg>>,PIzw>���c�X��^뀔��~]�dyVyz��egi�,�Rq����tz~��9�$��V`�t(Pb�r�Ü� %�-u��1f	
         [e] => 
         [d] => F"��3��4��!K�yF��R�lY�9�]Ξ��A��@�f��~�<�YPєG��=��TkTP�rl�Mԓ{�lŮ^��!��q�˂�7�|�f��lE+#�@.�GIH�tS�R.mbc�U~��7&w�ݥ�P.Fe�ϨU�@��m��X�ECsemjI$@/�$l��)�8�@���c�w�NRo��+!'�.��fvT7�=n")LQ�sdš�%zZ��G��{�{�1A^��v��E
         [p] => �>u)��1bǰK�r��pHE��k���LBE��y�'�3-�/��Pd��jeFV1����?�.O���:�bl2�z�U�{��{��*��A���<�}m4��J�Y�'�f@���
         [q] => ߦz\��96�=��V]"k��2w��>�r�袤�6�/�-Z�_��8!Y��I��L���_3Ym���.p�֏^��>�I:��oZ��"��=��8���뻢1��:�
         [dmp1] => z"�TW*��Ƴm�$�HQ�$0��sa��j� #�
         P�*�P��Q�G\42�a�26(�5�K�7zj��xj7��@e�$.6��b�Dq]]I}�L�m�d��54)@:���#
         [dmq1] => +��4}��\dc�R�K�Bw�\�E6�����%_�m$3蚞9�Fh�D�uz��$�8HPK�ˇԁ^�K�k�]e�g�>ºX�"<ƌ�`ė��&,9E��MS"��¥�)
         [iqmp] => !��߷�=�z�=ܰ7��V�6q�~���3V��t�P�$��O�kgv��3=W\ѝm���	�J���5^�K��a�t��~��U�.��!�l�v�#��z*���	���r
      )
      [type] => 0
   )

Example3

The following example below illustrates the usage of the openssl_pkey_new() function to read public key -

<?php
   echo "The hash of Welcome to Webdesigntutorialz is - ". hash('crc32b', 'Welcome to Webdesigntutorialz');
?>

Output

When the above code is executed, it will produce the following result -

-----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArAWYwKIaf3uN1bwww4R8 51ifDPGsreqr9cV3J1gSKC8kaAEsAQaZ/6gQlDBsUGs4nE8zKgOlcdOV/JApgAdz +CwoLJUgmEUkLDxOcWaCIUVuHAiyBGJaRKZ+MASy7wRG8hb+INd0/zoQRGXk3+jf Fj6rvSinVg49C4RAkRtkEdNnH0G5s6cedV6ec30DouRTuEQ/Fgizf0qaVtQbAURP n+/LT9V8c4LMaCyID7caTQOXAEjQqD4ooXGkOzmcsp03j2/F+T2mSIQRtI1gGJkZ oCMGX/xRxh5uemCcC4jcshn45Ikmb/S7WFqTCOC0e8l8CiTZ5Rr8EKFgtwliMds8 pQIDAQAB -----END PUBLIC KEY-----

Example4

The following example below illustrates the usage of the openssl_pkey_new() function to store public in a file -

<?php
   // Generate a new private (and public) key pair

   $privkey = openssl_pkey_new(array(
      "digest_alg"=>'md5',
      "private_key_bits" => 2048,
      "private_key_type" => OPENSSL_KEYTYPE_RSA,
   ));
   $keydetails = openssl_pkey_get_details($privkey);

   // To save the public key to a file 
   file_put_contents('mypublic.key', $keydetails['key']);
?>

Output

The contents of file mypublic.key is -

-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA3QxA7vWIz+F5t12/fl0H
vyavVy/ZNZFWGK6BID/koYeVA2wKdXx9De3gn0hs4sSrN3aV58ctuxDVx36rKvYd
AjKHfnfh7NmXnCEeUE4SgUUe0UUleoEMtsPP2Q8BC1HUjcC6SyJQKZG0bQqQlnAb
HL7ou2TNsjA/SiJbPD+0OpsLAcW1c/DeoM+TAkZo0JIlgxjcJ5ZlEbJ0Mxv6m9XK
k3bbMYHtKmZl+fzfPNcxCuK8Djnm5mYVR9KX1L86m1jz2kUQT/+wW84QRnZ7G+z8
4rQ77sZvWiIwwO2JmUvIsYeUxEP6/keZbDRuyO/2tWk/VxqQry4+Ktix/M2/iKWo
QQIDAQAB
-----END PUBLIC KEY-----


Alright guys! This is where we are going to be rounding up for this tutorial post. In our next tutorial, we will be studying about the PHP openssl_pkey_get_private() Function.

Feel free to ask your questions where necessary and we will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.

Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.

Thanks for reading and bye for now.