Convert P12 to PEM using PHP and OpenSSL

I am trying to convert some .p12 files to .pem.

On my mac, this works, without interaction, as I put passwords in the code, but when I use this code:

system('openssl pkcs12 -clcerts -nokeys -out apns-dev-cert.pem -in apns-dev-cert.p12 -passin pass:'); system('openssl pkcs12 -nocerts -out apns-dev-key.pem -in apns-dev-key.p12 -passout pass:1234 -passin pass:'); system('openssl rsa -in apns-dev-key.pem -out apns-dev-key-noenc.pem -passin pass:1234'); system('cat apns-dev-cert.pem apns-dev-key-noenc.pem > apns-dev.pem'); 

he makes empty files.

My access rights to files are 755. And for passin, passwords were set to nothing, therefore they are empty ... all the code here without a system () works in the mac terminal.

thank you for reading. hope you can help

+6
php openssl system macos
source share
1 answer
 $filename = 'apns-dev-cert.p12'; $password = '...'; $results = array(); $worked = openssl_pkcs12_read(file_get_contents($filename), $results, $password)); if($worked) { echo '<pre>', print_r($results, true), '</pre>'; } else { echo openssl_error_string(); } 

Try to run this snippet. Set $password to any passphrase to open the file. If there is no password, set it to null. I do not believe that you need openssl commands.

You should get the output with the desired private key, possibly inside $results['pkey'] .

If you see your private key, you can pass it to openssl_pkey_export to get it in PEM format, which you can then write to a file:

 $new_password = null; $result = null; $worked = openssl_pkey_export($results['pkey'], $result, $new_password); if($worked) { echo "<pre>It worked! Your new pkey is:\n", $result, '</pre>'; } else { echo openssl_error_string(); } 

Set $new_password to the desired password if you want.

This should work for you based on what I read on different pages of the documentation.


If you really want to continue the openssl command by proc_open around, consider proc_open instead of system , so that you can correctly catch error messages.

It is also possible that OpenSSL is trying to read the configuration file and does not have permission to do this, although it should give you an error about this.

+19
source share

All Articles