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

前端 未结 2 2034
悲&欢浪女
悲&欢浪女 2021-01-22 02:02

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 pkcs         


        
2条回答
  •  旧巷少年郎
    2021-01-22 02:36

    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!

提交回复
热议问题