Reputation: 790
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
Upvotes: 1
Views: 1007
Reputation: 1478
Without seeing what you are doing, I can tell you that the function you have there works. It may well depend on a few things as to why it's not working for you and without more information it's going to be hard to tell.
By default that function will convert your data to base64 and add a "BEGIN CERTIFICATE" Header and Footer - be aware that if you are calling that function to process a private key, you will need to call it like this:
$keyVal = der2pem($YOUR_KEY_DATA, 'PRIVATE KEY');
Upvotes: 1