phpopensslprivate-keycsrphp-openssl

how to create CSR in PHP?


I am trying to create CSR using PHP and OpenSSL extension,
but when I do that it gives me an error which says:

Failed to generate private key: error:2006D080:BIO routines:BIO_new_file:no such file

also php.ini is edited correctly, I added extension=openssl.

This is my code:

<?php

$dn = array(
    "countryName" => "US",
    "stateOrProvinceName" => "California",
    "localityName" => "San Francisco",
    "organizationName" => "My Company",
    "organizationalUnitName" => "IT",
    "commonName" => "mycompany.com",
    "emailAddress" => "admin@mycompany.com"
);

// Generate a new private (and public) key pair
$privkey = openssl_pkey_new(array(
    "private_key_bits" => 2048,
    "private_key_type" => OPENSSL_KEYTYPE_RSA,
));

if ($privkey === false) {
    die('Failed to generate private key: ' . openssl_error_string());
}

// Generate a certificate signing request
$csr = openssl_csr_new($dn, $privkey);

if ($csr === false) {
    die('Failed to generate CSR: ' . openssl_error_string());
}

// Export the CSR as a string
$csrout = '';
if (!openssl_csr_export($csr, $csrout)) {
    die('Failed to export CSR: ' . openssl_error_string());
}

echo $csrout;

// Optionally, save the private key
$pkeyout = '';
if (!openssl_pkey_export($privkey, $pkeyout, 'your-passphrase')) {
    die('Failed to export private key: ' . openssl_error_string());
}
file_put_contents('private_key.pem', $pkeyout);

?>

I use Laragon as web server.

How can i solve this problem?


Solution

  • the problem is that I have to install OpenSSL on my system,

    my system is Windows system then to install it I should go to this website :

    OpenSSL Binaries

    then after that choose the second choice in the table:

    enter image description here

    this is the link of it :

    Second choice

    then after that choose the completed version of OpenSSL :

    enter image description here

    after that, it will download the installer version of OpenSSL, just install it, and it will work.

    thanks