Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

macos - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
$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:
", $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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...