使用 PHP 和 OpenSSL 将 P12 转换为 PEM
我正在尝试将一些 .p12 文件转换为 .pem.
I'm trying to convert some .p12 files in to .pem.
在我的 mac 上它可以工作,没有交互,因为我将密码放入代码中,但是当我使用此代码时:
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');
它会生成空白文件.
我的文件权限是 755.对于 passin,密码被设置为空,所以这就是为什么它们是空白的......这里没有 system() 的所有代码都在 mac 终端中工作..
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
推荐答案
$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();
}
请尝试运行此代码段.将 $password
设置为打开文件所需的任何密码.如果没有密码,请将其设置为空.我认为您的 openssl
命令不需要一个.
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.
您应该获得所需私钥的输出,可能在$results['pkey']
中.
You should get output with the desired private key, probably inside $results['pkey']
.
如果你在那里看到你的私钥,那么你可以把它传递给 openssl_pkey_export
以 PEM 格式获取它,然后您可以将其写入文件:
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();
}
如果需要,请将 $new_password
设置为所需的 pkey 密码.
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.
如果您真的想继续使用 openssl
命令,请考虑使用 proc_open
而不是 system
,以便您可以正确捕获错误消息.
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.
也有可能是 OpenSSL 正在尝试读取配置文件,并且没有读取权限,尽管它应该给您一个错误.
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.
相关文章