Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Digital Sign PDF File with PHP and laravel

Hello i search a lot before make this question. I know there is a paied option to sign pdf setasign.com

I try to use php function:

openssl_pkcs7_sign( FULL_PATH . "/pdforiginal.pdf", //ORIGIANL PDF
                    FULL_PATH ."signedPDF.pdf", // SIGNED PDF
                    "file://" . FULL_PATH . "signing_cert.pem", 
                     array(  "file://" . FULL_PATH. "private_key.pem",""),array()); 

signing_cert.pem <- // I Dont understand what is this i just have private_key and public_key. I see some examples where people use private_key here.

My private key dont have password shoud i use blank "" or null ?

If anyone can give me little information about this topic would be really helpful.

like image 293
Carlos Branco Avatar asked Dec 24 '22 10:12

Carlos Branco


2 Answers

I find the solution. I use FPDI library to open pdf and use tcpdf library to sign it. That makes the process really simple.

require_once('tcpdf_include.php');

require_once "fpdi.php";

$pdf = new FPDI('P', 'mm', 'A4'); //FPDI extends TCPDF

$pages = $pdf->setSourceFile('document.pdf');



/*
NOTES:
 - To create self-signed signature: openssl req -x509 -nodes -days 365000 -newkey rsa:1024 -keyout tcpdf.crt -out tcpdf.crt
 - To export crt to p12: openssl pkcs12 -export -in tcpdf.crt -out tcpdf.p12
 - To convert pfx certificate to pem: openssl pkcs12 -in tcpdf.pfx -out tcpdf.crt -nodes
*/

$certificate = 'file://data/cert/tcpdf.crt';

// set additional information
$info = array(
    'Name' => 'TCPDF',
    'Location' => 'Office',
    'Reason' => 'Testing TCPDF',
    'ContactInfo' => 'http://www.tcpdf.org',
    );

for ($i = 1; $i <= $pages; $i++)
    {
        $pdf->AddPage();
        $page = $pdf->importPage($i);
        $pdf->useTemplate($page, 0, 0);


        // set document signature
        $pdf->setSignature($certificate, $certificate, 'tcpdfdemo', '', 2, $info);      

}
like image 177
Carlos Branco Avatar answered Dec 28 '22 07:12

Carlos Branco


Now Digital Certificates are being issued on cryptographic devices viz. USB Toke and Smartcards, and user will be holding the same, server might not have private key of the user's certificate. In web application, you need to get the pdf (hash) signed from USB Token or Smartcard connected to client's (browser) device.

You need to get pdf signed from browser itself, since, private key never comes out of USB Token. Please refer to answer https://stackoverflow.com/a/55676351/9659885

For PHP, easily available Java pdf library or any pdf component may be used through JavaBridge running on Tomcat through Apache proxy to digitally sign PDF from Browser USB token and PHP on server side.

like image 41
Bharat Vasant Avatar answered Dec 28 '22 08:12

Bharat Vasant