使用PHP将DER格式的.key文件加载到PEM [英] Load a .key file from DER format to PEM with PHP

查看:286
本文介绍了使用PHP将DER格式的.key文件加载到PEM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个代码可以进行转换,但是需要使用本机PHP函数来完成,因为它没有激活对运行exec的支持:

I have a code that makes the transformation but need to do it with native PHP functions because it is not activated support for running exec:

exec("openssl pkcs8 -inform DER -in 'archivo.key' -out 'archivo.key.pem' -passin pass:'lacontrasena'");

有人可以帮助我将其转换为本地PHP函数吗?它可以是openssl或库.

Someone can help me translate this into native PHP functions? It can be openssl or a library.

//已更新

这是我使用der2pem函数的代码:

This is my code using der2pem function:

function der2pem($der_data) {
   $pem = chunk_split(base64_encode($der_data), 64, "\n");
   $pem = "-----BEGIN PRIVATE KEY-----\n".$pem."-----END PRIVATE KEY-----\n";
   return $pem;
}
$keyfile = 'myFileDER.key';
$keyFileContent = file_get_contents($keyfile);
$pemContent = der2pem($keyFileContent);
file_put_contents('llavetemp.pem', $pemContent);

$private_key1 = openssl_pkey_get_private($pemContent);

var_dump($private_key1);

var_dump返回布尔值false

The var_dump return boolean false

推荐答案

您可以轻松使用uri2x的答案以及第一个Google搜索结果中的一些信息. PEM只是二进制DER文件的base64编码形式. 添加了一些元数据,您就可以完成所有操作.

You can easily use uri2x's answer and a few informations from the first google result. PEM is just the base64-encoded form of the binary DER file. Some Metadata is added and you can do everything with it.

因此,如果您将函数(由uri2x!发布)修改为以下内容:

so if you modify the function (posted by uri2x!) to the following:

function der2pem($der_data, $type='CERTIFICATE') {
   $pem = chunk_split(base64_encode($der_data), 64, "\n");
   $pem = "-----BEGIN ".$type."-----\n".$pem."-----END ".$type."-----\n";
   return $pem;
}

您现在可以将其命名为:

you can now call it:

$private_key=file_get_contents('archivo.key');
file_put_contents('archivo.key.pem',der2pem($private_key,'PRIVATE KEY');

您可以转换几乎所有需要在加密问题中转移的蜜蜂:

and you can transform nearly everything which needs to bee transferred in crypto-concerns:

//certificates
$private_key=file_get_contents('certificate');
echo der2pem($private_key,'CERTIFICATE');//here, certificate isn't even required because it's the default
//GPG/PGP Public Keys
$pgp_public_key=file_get_contents('pgp_public_key');
echo der2pem($private_key,'PGP PUBLIC KEY BLOCK');
//CSR
$certificate_signing_request=file_get_contents('csr');
echo der2pem($private_key,'CERTIFICATE REQUEST');

...和很多其他人!

这篇关于使用PHP将DER格式的.key文件加载到PEM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆