John Davidson

Extract public key from a PFX certificate to a .cer file with PHP OPENSSL

0 comments
Message:


I'm trying to create an encryption PHP-OPENSSL module to sign data and communicate with a third-party app. I have a digital .PFX certificate (cert.pfx) for this purpose.


I can open it and read it with openssl_pkcs12_read() with my passphrase.


The setup of the third party app ask me to upload the .cer public key of my certificate.


Because, i only have a .pfx file. I'm trying to extract the .cer public key from the PFX to create and upload the .cer file.


I'm using PHP-OPENSSL.


I tried to do it with this command :


 $pkeydet = openssl_pkey_get_details(openssl_pkey_get_public(file_get_contents("/path/to/cert.pfx")));

But it doesn't give the expected result (openssl_pkey_get_details() expects parameter 1 to be resource, boolean given). I'm not sure the reason why...


What this the correct way to achieve the creation of the .cer file?


Thank you :)



My Answer:
To extract the public key from a PFX certificate and save it to a .cer file using PHP OpenSSL, you can follow these steps:

1. Load the PFX certificate using openssl_pkcs12_read() function.
2. Extract the public key from the loaded certificate using openssl_pkey_get_public() function.
3. Get the details of the public key using openssl_pkey_get_details() function.
4. Save the public key to a .cer file.

Here is an example code snippet to achieve this:

php

// Load the PFX certificate
$cert = file_get_contents("/path/to/cert.pfx");
$passphrase = "your_passphrase";
openssl_pkcs12_read($cert, $certs, $passphrase);

// Extract the public key
$publicKey = openssl_pkey_get_public($certs['cert']);

// Get the details of the public key
$pkeyDetails = openssl_pkey_get_details($publicKey);

// Save the public key to a .cer file
file_put_contents("/path/to/public_key.cer", $pkeyDetails['key']);

echo "Public key extracted and saved to public_key.cer file.";
?>


Make sure to replace "/path/to/cert.pfx" with the actual path to your PFX certificate file and set the correct passphrase for the certificate. After running this code, the public key will be extracted from the PFX certificate and saved to a .cer file.

Rate this post

5 of 5 based on 9286 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us