How to Generate and Validate PDF Digital Signatures in PHP

How to Generate and Validate PDF Digital Signatures in PHP

Introduction

With digital transactions and document processing becoming more common, ensuring that PDF documents are authentic and tamper-proof is crucial.

Using digital signatures in PDFs, you can:

Verify document authenticity and prevent forgery
Ensure documents remain unchanged after signing
Legally secure contracts, invoices, and reports
Automate digital signing and validation in PHP

In this guide, we’ll cover:

Generating a digital signature for PDFs in PHP
Embedding cryptographic signatures with TCPDF
Validating a digitally signed PDF
Ensuring document security with cryptographic certificates

By the end, you'll be able to sign PDFs dynamically and verify their authenticity in PHP. 🚀

1. Understanding Digital Signatures in PDFs

A digital signature is a cryptographic method that binds the identity of the signer to the document. It ensures:

Integrity – The document hasn’t been altered.
Authenticity – The signer is verified.
Non-repudiation – The signer cannot deny signing the document.

🔹 PDF Digital Signature = Cryptographic Hash + Certificate + Signer Identity

To implement digital signatures, we use TCPDF, an advanced PHP library for handling PDFs securely.

2. Installing TCPDF for PDF Digital Signatures

TCPDF supports native digital signatures in PDFs.

Install TCPDF via Composer:

composer require tecnickcom/tcpdf

Include TCPDF in Your PHP Script:

require 'vendor/autoload.php';

use TCPDF;

Now, we can generate digitally signed PDFs in PHP.

3. Generating a Digital Signature for a PDF in PHP

Before signing a document, you need a cryptographic certificate (.pem file).

Generate a Self-Signed Certificate with OpenSSL

openssl req -x509 -newkey rsa:4096 -keyout private_key.pem -out certificate.pem -days 365

🔹 This generates:
certificate.pem – The public key (used for verification)
private_key.pem – The private key (used for signing)

4. Digitally Signing a PDF in PHP Using TCPDF

Example: Add a Digital Signature to a PDF

require 'vendor/autoload.php';

use TCPDF;

// Create PDF
$pdf = new TCPDF();
$pdf->SetCreator('My Company');
$pdf->SetAuthor('John Doe');
$pdf->SetTitle('Signed Document');
$pdf->AddPage();
$pdf->SetFont('helvetica', '', 12);
$pdf->Cell(0, 10, 'This document is digitally signed!', 0, 1, 'C');

// Set Digital Signature
$certificate = 'file://certificate.pem';
$pdf->setSignature($certificate, $certificate, 'mypassword', '', 2, [
    'Name' => 'John Doe',
    'Location' => 'New York, USA',
    'Reason' => 'Document Verification',
    'ContactInfo' => 'johndoe@example.com'
]);

// Output Signed PDF
$pdf->Output('signed_document.pdf', 'F');

echo "PDF signed successfully!";

Explanation:

setSignature() – Embeds the digital signature in the PDF.
Uses .pem certificate for signing the document.
Signature metadata includes signer details.

🔹 The signed PDF will now show a digital signature field in Adobe Acrobat!

5. Validating a Digitally Signed PDF

To verify a signed PDF, open it in Adobe Acrobat Reader and check the Signatures Panel:

  1. Open the PDF in Adobe Acrobat Reader.
  2. Click on "Signatures" in the left panel.
  3. Acrobat will show if the signature is valid or if the document has been altered.

If valid, the document is authentic and hasn’t been modified.
If invalid, the document has been altered after signing.

🔹 For server-side validation, use OpenSSL in PHP:

$certificate = file_get_contents('certificate.pem');
$valid = openssl_x509_checkpurpose($certificate, X509_PURPOSE_ANY);
echo $valid ? "Valid Signature!" : "Invalid Signature!";

6. Restricting Modifications After Signing

To prevent changes after signing, restrict PDF permissions.

Example: Prevent Editing and Copying in a Signed PDF

$pdf->SetProtection(['modify', 'copy'], 'userpassword', 'ownerpassword');
$pdf->Output('secure_signed.pdf', 'F');

Prevents unauthorized modifications or text copying.

7. Automating PDF Signing for Uploaded Documents

You can automate the signing process for uploaded PDFs.

Example: Automatically Sign a PDF on Upload

if ($_FILES['pdf']['error'] == 0) {
    $uploadDir = "uploads/";
    $pdfPath = $uploadDir . basename($_FILES['pdf']['name']);

    if (move_uploaded_file($_FILES['pdf']['tmp_name'], $pdfPath)) {
        // Sign the uploaded PDF
        signPDF($pdfPath, "signed_".$pdfPath);
        echo "PDF uploaded and signed successfully!";
    } else {
        echo "Upload failed!";
    }
}

function signPDF($source, $destination) {
    $pdf = new TCPDF();
    $pdf->setSourceFile($source);
    $pdf->AddPage();
    $tplIdx = $pdf->importPage(1);
    $pdf->useTemplate($tplIdx);

    $certificate = 'file://certificate.pem';
    $pdf->setSignature($certificate, $certificate, 'mypassword', '', 2);
    $pdf->Output($destination, 'F');
}

Automatically signs any uploaded PDF document.

8. Encrypting and Securing a Digitally Signed PDF

For additional security, encrypt the PDF to prevent unauthorized access.

Example: Encrypt a Signed PDF

$pdf->SetProtection(['print', 'copy'], 'userpassword', 'ownerpassword');
$pdf->Output('encrypted_signed.pdf', 'F');

Requires a password to open or modify the signed PDF.

9. Verifying Signatures with PHP (OpenSSL)

To check if a signature matches the certificate, use OpenSSL.

Example: Verify a Certificate in PHP

$cert = file_get_contents('certificate.pem');
$valid = openssl_x509_checkpurpose($cert, X509_PURPOSE_ANY);
echo $valid ? "Certificate is Valid!" : "Invalid Certificate!";

This checks whether the certificate used for signing is valid.

10. Best Practices for Digital Signature Implementation in PHP

Use a strong RSA key (4096-bit) for secure signing.
Always validate signed PDFs before processing.
Restrict modifications after signing to ensure authenticity.
Encrypt signed PDFs for an extra layer of security.
Log signature events for auditing and compliance.

Conclusion

With TCPDF and OpenSSL, you can generate and validate digital signatures for PDFs in PHP.

Digitally sign PDFs to ensure authenticity.
Validate signatures to check document integrity.
Prevent unauthorized modifications with encryption.
Automate signing for uploaded documents.

By implementing these best practices, you can build a secure document verification system in PHP! 🚀

Leave a Reply