Get and Verify Digital Signature in PDF in C#

Creating digital signature in PDF is widely used to protect PDF files. So you need to get and verify the digital signature when you view some PDF files with digital signature. This article shows you a solution of getting and verifying the digital signature in PDF by using Spire.PDF with C# code.

Make sure Spire.PDF for .NET (version 2.9 or above) has been installed correctly. Add Spire.PDF.dll as reference in the downloaded Bin folder thought the below path: "..\Spire.PDF\Bin\NET4.0\ Spire.PDF.dl".

Here comes to the C# code snippet of how to get and verify digital signature as below:

Load a PDF file with digital signature.

[C#]
string filename = @"..\..\DigitalSignature.pdf";

Get all signatures from the PDF:

[C#]
List<PdfSignature> signatures = new List<PdfSignature>();
using (var doc = new PdfDocument(filename))
{
   var form = (PdfFormWidget)doc.Form;
   for (int i = 0; i < form.FieldsWidget.Count; ++i)
   {
        var field = form.FieldsWidget[i] as PdfSignatureFieldWidget;

        if (field != null && field.Signature != null)
        {
            PdfSignature signature = field.Signature; 
            signatures.Add(signature);
         }
    }
}

Get the first signature:

[C#]
PdfSignature signatureOne = signatures[0];

Verify the signature:

[C#]
try
{
  bool bSignature = signatureOne.VerifySignature();
}
catch (Exception ex)
{
     Console.WriteLine(ex.Message);
     Console.ReadLine();
}

Get the certification of signature:

[C#]
X509Certificate2 certificate = signatureOne.Certificate as X509Certificate2;

Get the date of signature:

[C#]
DateTime date = signatureOne.Date;

Get the date on which the signature starts and ends valid:

[C#]
DateTime validStart = certificate.NotBefore;
DateTime validEnd = certificate.NotAfter;

Get the version of the certificate:

[C#]
int version = certificate.Version;

Get the subject distinguished name from the certificate:

[C#]
string subject = certificate.Subject;

Please check the effective screenshot as below:

PDF Digital Signature