Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Digitally signing a PDF, using PHP, Zend, and openssl

I'm trying to build a simple PDF document signing routine, using PHP, openssl, and the Zend framework (for pdf redering/handling).

I've found this, but it simply won't work, Zend is not able to open any pdf's, not even Zend's own test pdf and Zend will not report why, only that it 'cannot'.

I'm pretty sure I would be able to create the keys/certs effectively as that is well documented, but is there a solid approach to attaching the generated certificate to the PDF as the above Zend extension suggests it once did?

function DigiSignPDF ($pdf_sign_request) {
    if (get_magic_quotes_gpc()) {
        $new_pdf = stripslashes($pdf_sign_request['raw_pdf']);
    } else {
        $new_pdf = $pdf_sign_request['raw_pdf'];
    }
    $test_pdf = stripslashes(file_get_contents('path/Some.pdf'));
    $test_pdf2 = ('path/Some.pdf');
    $pdf = Zend_Pdf::load($new_pdf2);
    //below is the signing code, from another library, it works as long as Zend_Pdf works
    $certificate = file_get_contents('path/certificate.p12');
    $certificatePassword = 'test123';

    if (empty($certificate)) {
        throw new Zend_Pdf_Exception('Cannot retrieve/generate the certificate.');
    }
    $pdf->attachDigitalCertificate($certificate,$certificatePassword);
    $eSig_pdf = $pdf->render();
    file_put_contents('path/signed_pdf.pdf', $eSig_pdf);
}

Edit, adding code: The above only works if I use 'test_pdf2' as the input for Zend_Pdf. It recognizes the cert as binary with no problems, but I need to be able to pass the PDF without ever writing it to disk.

like image 469
jbrain Avatar asked Jun 05 '12 19:06

jbrain


2 Answers

TCPDF supports signing of pdf files. Maybe you find something useful in the source code.

like image 102
Oliver Avatar answered Sep 20 '22 17:09

Oliver


Adding my solution as answer, per halfer's advice: Solved this one, because I was passing the content to Zend_Pdf as a string, i should have been using Zend_Pdf::parse($new_pdf);, as it very likely says in the manual. (oops)

Further; I solved pretty much ALL of my problems with digitally signing PDFs of various versions and form constituents by moving to TCPDF, as several of the articles here suggest. A similar caveat was met with TCPDF though, when using strings, ensure that you are using TCPDF's 'writeHTMLCell' instead of 'writeHTML'. And watch for PHPs 'magic_quotes', errant whitespace, encoding, and goblins.

like image 30
jbrain Avatar answered Sep 23 '22 17:09

jbrain