Load a .key file from DER format to PEM with PHP

2019-08-24 16:47发布

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'");

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

//Updated

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);

The var_dump return boolean false

2条回答
姐就是有狂的资本
2楼-- · 2019-08-24 16:57

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.

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');

...and many others!

查看更多
ゆ 、 Hurt°
3楼-- · 2019-08-24 17:05

See dan's comment on php.net:

Use the following code to convert from DER to PEM and PEM to DER.

<?php
$pem_data = file_get_contents($cert_path.$pem_file);
$pem2der = pem2der($pem_data);

$der_data = file_get_contents($cert_path.$der_file);
$der2pem = der2pem($der_data);

function pem2der($pem_data) {
   $begin = "CERTIFICATE-----";
   $end   = "-----END";
   $pem_data = substr($pem_data, strpos($pem_data, $begin)+strlen($begin));   
   $pem_data = substr($pem_data, 0, strpos($pem_data, $end));
   $der = base64_decode($pem_data);
   return $der;
}

function der2pem($der_data) {
   $pem = chunk_split(base64_encode($der_data), 64, "\n");
   $pem = "-----BEGIN CERTIFICATE-----\n".$pem."-----END CERTIFICATE-----\n";
   return $pem;
}
查看更多
登录 后发表回答