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

jbrain picture jbrain · Jun 5, 2012 · Viewed 24.7k times · Source

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.

Answer

Oliver picture Oliver · Jun 5, 2012

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