Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert P12 to PEM using PHP and OpenSSL

I'm trying to convert some .p12 files in to .pem.

On my mac it works, with no interaction as i put the 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');

it makes blank files.

My file permissions are 755. and for the passin the passwords were set to nothing so thats why they are blank... all the code here without the system() works in the mac terminal..

thanks for reading. hope you can help

like image 809
user633268 Avatar asked Mar 24 '11 16:03

user633268


People also ask

Is PKCS12 same as PEM?

PKCS12 - A Microsoft private standard that was later defined in an RFC that provides enhanced security versus the plain-text PEM format. This can contain private key and certificate chain material. Its used preferentially by Windows systems, and can be freely converted to PEM format through use of openssl.


1 Answers

$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();
}

Please try running this snippet. Set $password to whatever passphrase is needed to open the file. If there's no password, set it to null. I don't believe one is needed from your openssl commands.

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

If you see your private key there, then 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 your desired pkey password, if you want one.

This should work for you, based on what I'm reading on the various documentation pages.


If you really want to continue using the openssl command by shelling out, please consider using proc_open instead of system, so that you can properly catch error messages.

It's also possible that OpenSSL is trying to read the config file, and doesn't have permission to so, though it should give you an error about that.

like image 135
Charles Avatar answered Oct 23 '22 05:10

Charles