ImageGear .NET v24.12 - Updated
Work with PDF Signatures
User Guide > How to Work with... > PDF > How to... > Work with PDF Signatures

A PDF document can be signed with a digital signature, allowing you to detect and prevent unauthorized changes to a document, as well as authenticate the signer. Also, digital signatures allow you to define permissions for changes that are to be permitted, such as adding annotations or filling in and signing forms.

This topic includes:

Signature Types

There are three types of signatures in PDF: certification signatures, approval signatures, and usage rights signature.

ImageGear makes working with signatures simple. It allows for both signing and verification. After signing and saving a document, it will contain the signature(s) inside the file. After loading a signed PDF document, its signatures may be verified and the result will indicate whether the document was changed after signing and whether the signatures can be authenticated.

Signature Fields

Certification and approval signatures are associated with a SignatureField through the field's Signature property. You can assign a signature to this property to prepare the actual signing or read it for verification purposes. If the field has not been signed, the Signature property is null.

Signature Handlers

A signature handler is used to specify the algorithm that is used to encode the signature. ImageGear provides a readily available implementation of the most common type of algorithm: PKCS7SignatureHandler. This implementation uses the PKCS#7 detached method (SubFilter adbe.pkcs7.detached) and takes a digital certificate from file or directly as a parameter. Although this sounds complicated, it is really easy to use (see the sample in Signing a Document below).

Signing a Document

Signing a document has the following restrictions:  

To sign a PDF document:

  1. Create an instance of an ApprovalSignature and fill out the properties. The most important and required property is the Handler property, which defines the type of algorithm used when signing the document.
  2. When the signature is created, it must be assigned to the SignatureField that is to be signed.
  3. The document will not actually be signed until the document is saved. At that moment, the signature's handler will be called to calculate the actual signature data, which then is stored directly into the file to obtain the signed PDF document.

The following example illustrates the functionality of signing a PDF document with an approval signature.

C#
Copy Code
using System;
using System.IO;
using ImageGear.Formats;
using ImageGear.Formats.PDF;
using ImageGear.Formats.PDF.Forms;
using ImageGear.Formats.PDF.Signatures;

static void Main(string[] args)
{
    // PDF initialization.
    ImGearFileFormats.Filters.Add(ImGearPDF.CreatePDFFormat());
    ImGearPDF.Initialize();

    using (Stream stream = new FileStream(@"C:\UnsignedFile.pdf", FileMode.Open, FileAccess.Read))
    {
        using (ImGearPDFDocument pdfDocument = ImGearFileFormats.LoadDocument(stream) as ImGearPDFDocument)
        {
            // Create form if it does not exist.
            if (pdfDocument.Form == null)
                pdfDocument.CreateForm();

            // Create new signature field for keeping the signature.
            SignatureField signatureField = pdfDocument.Form.CreateSignatureField(
                    "my_signature", pdfDocument.Pages[0] as ImGearPDFPage, new ImGearPDFFixedRect(0, 0, 0, 0));

            // Add new approval signature to the signature field.
            // The Handler property must be specified.
            signatureField.Signature = new ApprovalSignature(pdfDocument)
            {
                SignerName = "George Williams",
                SigningReason = "I have read and agree to this document",
                Handler = new PKCS7SignatureHandler(@"C:\my_certificates.pfx", "password")
            };

            // The signature is applied to the document when saving.
            pdfDocument.Save(@"C:\Signed.pdf", ImGearSavingFormats.PDF, 0, 0,
                    pdfDocument.Pages.Count, ImGearSavingModes.OVERWRITE);
        }
    }

    // Free PDF engine.
    ImGearPDF.Terminate();
}
VB.NET
Copy Code
Imports System.IO
Imports ImageGear.Formats
Imports ImageGear.Formats.PDF
Imports ImageGear.Formats.PDF.Forms
Imports ImageGear.Formats.PDF.Signatures

Public Shared Sub Main(args As String())

    ' PDF initialization.
    ImGearFileFormats.Filters.Add(ImGearPDF.CreatePDFFormat())
    ImGearPDF.Initialize()

    ' Load existing unsigned PDF document.
    Using stream As Stream = New FileStream("C:\UnsignedFile.pdf", FileMode.Open, FileAccess.Read)

        Using pdfDocument As ImGearPDFDocument = DirectCast(ImGearFileFormats.LoadDocument(stream), ImGearPDFDocument)

            ' Create form if it does not exist.
            If pdfDocument.Form Is Nothing Then
                pdfDocument.CreateForm()
            End If

            ' Create new signature field for keeping the signature.
            Dim signatureField As SignatureField = pdfDocument.Form.CreateSignatureField("cert_signature",
                DirectCast(pdfDocument.Pages(0), ImGearPDFPage), New ImGearPDFFixedRect(0, 0, 0, 0))

            ' Add New approval signature to the signature field.
            ' The Handler property must be specified.
            signatureField.Signature = New ApprovalSignature(pdfDocument) With {
                .SignerName = "George Williams",
                .SigningReason = "I have read and agree to this document",
                .Handler = New PKCS7SignatureHandler("C:\my_certificates.pfx", "password")
            }

            ' The signature is applied to the document when saving.
            pdfDocument.Save("C:\SignedFile.pdf", ImGearSavingFormats.PDF, 0, 0,
                                pdfDocument.Pages.Count, ImGearSavingModes.OVERWRITE)
        End Using
    End Using

    ' Free PDF engine.
    ImGearPDF.Terminate()
End Sub

Verifying a Document

Before verifying signatures, you need to tell ImageGear.NET which certificates are trusted by the user via the ImGearPDF.TrustedCertificates property. Because certificate validity and document integrity are checked, if the certificate used to sign the PDF is not trusted, an error will occur upon verification.

Verify signatures in a document by using the ImGearPDFDocument.VerifySignatures method. This method attempts to verify all signatures present in the document, and returns either SignatureVerificatonResult.OK or the result for the first signature that fails verification.

To verify each signature separately, you can loop through all of the signatures listed in ImGearPDFDocument.Signatures. This is illustrated in the example below.

C#
Copy Code
using System;
using System.IO;
using ImageGear.Formats;
using ImageGear.Formats.PDF;
using ImageGear.Formats.PDF.Forms;
using ImageGear.Formats.PDF.Signatures;

static void Main(string[] args)
{
    // PDF initialization.
    ImGearFileFormats.Filters.Add(ImGearPDF.CreatePDFFormat());
    ImGearPDF.Initialize();

    // Trust any user-specified certificates (DER or PEM format) to verify a signer's identity when signing.
    // If the certificate used to sign the PDF is not trusted, an error will occur upon verification.
    ImGearPDF.TrustedCertificates.Import(@"C:\my_signing_certificate.der");

    using (Stream stream = new FileStream(@"C:\Signed.pdf", FileMode.Open, FileAccess.Read))
    {
        using (ImGearPDFDocument pdfDocument = ImGearFileFormats.LoadDocument(stream) as ImGearPDFDocument)
        {
            // Enumerate and check all signatures.
            foreach (Signature signature in pdfDocument.Signatures)
            {
                SignatureVerificationResult result = signature.Verify();
                if (result != SignatureVerificationResult.OK)
                    throw new Exception("Signature verification failed!");
            }
        }
    }

    // Free PDF engine.
    ImGearPDF.Terminate();
}
VB.NET
Copy Code
Imports System.IO
Imports ImageGear.Formats
Imports ImageGear.Formats.PDF
Imports ImageGear.Formats.PDF.Forms
Imports ImageGear.Formats.PDF.Signatures

Public Shared Sub Main(args As String())

    ' Add PDF file format filter to the list of used file formats.
    ImGearFileFormats.Filters.Add(ImGearPDF.CreatePDFFormat())

    ' PDF initialization.
    ImGearPDF.Initialize()

    '' Trust any user-specified certificates (DER Or PEM format) to verify a signer's identity when signing.
    '' If the certificate used to sign the PDF Is Not trusted, an error will occur upon verificaton.
    ImGearPDF.TrustedCertificates.Import("C:\my_signing_certificate.der")

    ' Load existing unsigned PDF document.
    Using stream As Stream = New FileStream("C:\Signed.pdf", FileMode.Open, FileAccess.Read)

        Using pdfDocument As ImGearPDFDocument = DirectCast(ImGearFileFormats.LoadDocument(stream), ImGearPDFDocument)

            ' Enumerate and check all signatures.
            For Each signature As Signature In pdfDocument.Signatures

                Dim result As SignatureVerificationResult = signature.Verify()
                If result <> SignatureVerificationResult.OK Then
                    Throw New Exception("Signature verification failed!")
                End If
            Next
        End Using
    End Using

    ' Free PDF engine.
    ImGearPDF.Terminate()
End Sub

 

See Also