I need to sign PDF documents on PHP, I'm using TCPDF library to do it
The problem is my .CER and my .Key files are in DER format and openssl_pkcs7_sign() function can load the private key if is this format
If I use openssl commands on my terminal to convert my keys from binary DER format to ASCII everything works but I don't want to use exec function to call system functions through PHP.
After a little bit of research I found this question: Load a .key file from DER format to PEM with PHP On of the answers propose open the file, get the content and use convertion.
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;
}
But when I use this function to convert my data the result is different to the file generated by openssl on the console and the function openssl_pkcs7_sign() throws me again the error
UPDATE
This is my PHP code to convert my file:
<?php
$myKey = 'p-key.key';
$private_key = file_get_contents($myKey);
echo der2pem($private_key,'PRIVATE KEY');
file_put_contents('p-key.key.pem', der2pem($private_key,'PRIVATE KEY'));
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;
}
This is my openssl command:
openssl pkcs8 -in p-key.key -out p-key.key.pem -inform DER -outform PEM
Is there an explanation for this?
How is the correct way to do it?
Should I use the exec to solve my problem?
Thanks a lot in advance
Let me know if you need more information