Debug School

rakesh kumar
rakesh kumar

Posted on

How to generate private key in PEM format in php

To generate a new private key in PEM format in PHP, you can use the OpenSSL library. Here's an example code snippet that demonstrates how to generate a new private key in PEM format:

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

// Create a new private key
$privateKey = openssl_pkey_new($config);

// Extract the private key to a string in PEM format
openssl_pkey_export($privateKey, $pemKey);

// Output the private key
echo $pemKey;
Enter fullscreen mode Exit fullscreen mode

Image description

This code generates a new RSA private key with 2048 bits and the SHA-512 hash function, and then extracts the private key to a string in PEM format using the openssl_pkey_export() function. The resulting PEM key is then output to the console, but you could also write it to a file or use it in your PHP code as needed.

Note that you may need to adjust the parameters in the $config array to suit your specific needs, such as choosing a different key size or hash algorithm.

If you have a private key in a format other than PEM and you need to convert it to PEM format before using the openssl_pkey_get_private() function in PHP, you can use the OpenSSL library in PHP to perform the conversion.

Assuming you have a private key in DER format, you can convert it to PEM format using the following code:

$derKey = file_get_contents('private_key.der');
$pemKey = openssl_pkey_get_private($derKey);
openssl_pkey_export($pemKey, $pemKeyString);
file_put_contents('private_key.pem', $pemKeyString);
Enter fullscreen mode Exit fullscreen mode

Image description

Replace private_key.der with the name of your private key file in DER format, and private_key.pem with the desired name of the output file in PEM format. If your private key is in a different format, adjust the code accordingly.

This code reads the private key from the DER file, converts it to a PEM format using openssl_pkey_get_private() and openssl_pkey_export(), and then writes the resulting PEM key to a file. You can then use the PEM key with openssl_pkey_get_private() to load it into PHP.

Top comments (0)