Categories
Share on twitter
Share on facebook
Share on linkedin
Digitally sign and verify PDF documents

Create and Validate PDF Digital Signatures in C#

The Syncfusion PDF Library  is a .NET PDF library that allows users to create and validate PDF digital signatures in C# and VB.NET.

A PDF digital signature is basically a secure way to ensure the following:

  • Integrity of the document: Ensures that the document has not been altered somewhere in the workflow.
  • Authenticity of the document: Ensures the authenticity of the person who signed the electronic document.
  • Nonrepudiation: The signatory cannot deny authorship.

The complete details to create and validate PDF digital signatures in C# are explained in the following topics in this post:

Create PDF digital signatures

To create a PDF digital signature, you need a digital ID. You can create a self-signed digital ID using Adobe Reader. The digital ID contains a private key and certificates with a public key.

You can follow these four steps to sign an existing PDF document using Syncfusion PDF Library:

  1. Load the existing PDF document.
  2. Load the digital ID with password.
  3. Create a signature with a loaded digital ID (this involves signing the PDF, as well).
  4. Save the PDF document.

The following code example shows how to create a PDF digital signature in C#.

using Syncfusion.Pdf.Parsing;
using Syncfusion.Pdf.Security;
class Program
{
    static void Main(string[] args)
    {
        //Load existing PDF document.
        PdfLoadedDocument document = new PdfLoadedDocument("PDF_Succinctly.pdf");

        //Load digital ID with password.
        PdfCertificate certificate = new PdfCertificate(@"DigitalSignatureTest.pfx", "DigitalPass123");

        //Create a signature with loaded digital ID.
        PdfSignature signature = new PdfSignature(document, document.Pages[0], certificate, "DigitalSignature");

        //Save the PDF document.
        document.Save("SignedDocument.pdf");

        //Close the document.
        document.Close(true);
    }
}

By executing this code example, you will get a PDF document similar to the following screenshot.

Digitally signed PDF document—Syncfusion PDF Library.
Digitally signed PDF document—Syncfusion PDF Library.

To get a valid green tick in your Adobe Acrobat Reader, as seen in the previous screenshot, you will have to register the self-signed digital ID into the trusted source.

Otherwise, to get a valid signature in any Adobe Acrobat Reader, your digital ID should be an AATL-enabled signing credential.

Create PDF digital signatures with custom appearances

PDF digital signatures with custom appearances help users easily identify the digital signatures in a PDF page. You can create your own appearance by drawing the signature, signer information, etc.

To create a visible digital signature, you must set the bounds of the signature. You can also customize the appearance of the signature using the Appearance property available in the class PdfSignature. You can draw any shape, text, or image for the signature appearance.

The following code example shows how to create a PDF digital signature in C# with a custom appearance.

using Syncfusion.Pdf.Graphics;
using Syncfusion.Pdf.Parsing;
using Syncfusion.Pdf.Security;
class Program
{
    static void Main(string[] args)
    {
        //Load existing PDF document.
        PdfLoadedDocument document = new PdfLoadedDocument("PDF_Succinctly.pdf");

        //Load digital ID with password.
        PdfCertificate certificate = new PdfCertificate(@"DigitalSignatureTest.pfx", "DigitalPass123");

        //Create a signature with loaded digital ID.
        PdfSignature signature = new PdfSignature(document, document.Pages[0], certificate, "DigitalSignature");
        //Set bounds to the signature.
signature.Bounds = new System.Drawing.RectangleF(40, 40, 350, 100);

        //Load image from file.
        PdfImage image = PdfImage.FromFile("signature.png");
        //Create a font to draw text.
        PdfStandardFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 15);

        //Drawing text, shape, and image into the signature appearance.
signature.Appearance.Normal.Graphics.DrawRectangle(PdfPens.Black,PdfBrushes.White, new System.Drawing.RectangleF(50, 0, 300, 100));
        signature.Appearance.Normal.Graphics.DrawImage(image, 0, 0,100,100);
signature.Appearance.Normal.Graphics.DrawString("Digitally Signed by Syncfusion", font,PdfBrushes.Black, 120, 17);
        signature.Appearance.Normal.Graphics.DrawString("Reason: Testing signature", font, PdfBrushes.Black, 120, 39);
        signature.Appearance.Normal.Graphics.DrawString("Location: USA", font, PdfBrushes.Black, 120, 60);

        //Save the PDF document.
        document.Save("SignedAppearance.pdf");

        //Close the document.
        document.Close(true);
    }
}

By executing this code example, you will get a PDF document similar to the following screenshot.

PDF digital signature with appearance customized —Syncfusion PDF Library.
PDF digital signature with appearance customized —Syncfusion PDF Library.

Create PDF digital signatures with CAdES and different hashing algorithms

CAdES (CMS Advanced Electronic Signatures) is a standard developed by the European Telecommunications Standard Institute (ETSI) to facilitate secure, paperless transactions throughout the EU. You can find more details on the ETSI site.

By default, the Syncfusion PDF Library generates digital signatures with CMS (part 2 of the PAdES) standard and SHA 256 hashing algorithm.

You can change the digital signature standard to CAdES (part 3 of the PAdES) using the property CryptographicStandard available in the class PdfSignatureSettings. PdfSignatureSettings also has the property DigestAlgorithm to change the hashing algorithm.

The following code example shows how to create a PDF digital signature in C# with CAdES standard with a different hashing algorithm.

using Syncfusion.Pdf.Parsing;
using Syncfusion.Pdf.Security;
class Program
{
static void Main(string[] args)
{
//Load existing PDF document.
PdfLoadedDocument document = new PdfLoadedDocument("PDF_Succinctly.pdf");

//Load digital ID with password.
PdfCertificate certificate = new PdfCertificate(@"DigitalSignatureTest.pfx", "DigitalPass123");

//Create a signature with loaded digital ID.
PdfSignature signature = new PdfSignature(document, document.Pages[0], certificate, "DigitalSignature");

//Changing the digital signature standard and hashing algorithm.
signature.Settings.CryptographicStandard = CryptographicStandard.CADES;
signature.Settings.DigestAlgorithm = DigestAlgorithm.SHA512;

//Save the PDF document.
document.Save("SigneCAdES.pdf");

//Close the document.
document.Close(true);
}
}

By executing this code example, you will get a PDF document with the following digital signature properties.

Digital signature properties in a PDF document.
Digital signature properties in a PDF document.

Add multiple digital signatures in a single PDF document

As an example, let’s say a book publisher is creating a contract for a book author. Such a contract could contain one certification signature from the publisher with terms and conditions and another approval signature from the author. So here, you need to add multiple digital signatures to a single PDF document.

You can add multiple digital signatures in a single PDF document by appending additional signatures to an already-signed PDF file.

In the following sample, we have added the first digital signature using the digital ID “TestAgreement.pfx”. This is called the first revision.

The second revision contains the digital signature with digital ID “DigitalSignatureTest.pfx”.

The following code example shows how to create a PDF with multiple digital signatures in C#.

using Syncfusion.Pdf.Parsing;
using Syncfusion.Pdf.Security;
class Program
{
static void Main(string[] args)
{
//Load existing PDF document.
PdfLoadedDocument document = new PdfLoadedDocument("PDF_Succinctly.pdf");

//Load digital ID with password.
PdfCertificate certificate = new PdfCertificate(@"TestAgreement.pfx", "Test123");

//Create a revision 2 signature with loaded digital ID.
PdfSignature signature = new PdfSignature(document, document.Pages[0], certificate, "DigitalSignature1");

//Changing the digital signature standard and hashing algorithm.
signature.Settings.CryptographicStandard = CryptographicStandard.CADES;
signature.Settings.DigestAlgorithm = DigestAlgorithm.SHA512;

MemoryStream stream = new MemoryStream();

//Save the PDF document.
document.Save(stream);

//Close the document.
document.Close(true);

PdfLoadedDocument document2 = new PdfLoadedDocument(stream);
//Load digital ID with password.
PdfCertificate certificate2 = new PdfCertificate(@"DigitalSignatureTest.pfx", "DigitalPass123");

//Create a signature revision 2 with loaded digital ID.
PdfSignature signature2 = new PdfSignature(document2, document2.Pages[0], certificate2, "DigitalSignature2");

//Change the digital signature standard and hashing algorithm.
signature2.Settings.CryptographicStandard = CryptographicStandard.CADES;
signature2.Settings.DigestAlgorithm = DigestAlgorithm.SHA512;

//Save the PDF document.
document2.Save("MultipleSignature.pdf");

//Close the document.
document2.Close(true);}

By executing this code example, you will get a PDF document with two digital signatures.

PDF document with more than one digital signature.
PDF document with more than one digital signature.

Digitally sign a PDF document using Windows certificate store

A secure way to store a digital ID is using a Windows certificate store. If a root certificate is added in a Windows certificate store, you don’t need to add and trust each of the certificates that are already present in a Windows certificate store manually.

You can retrieve the digital ID “X509Certificate2” from the Windows certificate store and use it to add a digital signature to a PDF document.

The following code example shows how to create a PDF digital signature in C# using a Windows certificate store.

using Syncfusion.Pdf.Parsing;
using Syncfusion.Pdf.Security;
using System.Security.Cryptography.X509Certificates;

class Program
{
static void Main(string[] args)
{
//Initialize the Windows store.
X509Store store = new X509Store("MY", StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
X509Certificate2Collection collection = (X509Certificate2Collection)store.Certificates;
//Find the certificate using thumb print.
X509Certificate2Collection fcollection = (X509Certificate2Collection)collection.Find(X509FindType.FindByThumbprint, "F85E1C5D93115CA3F969DA3ABC8E0E9547FCCF5A", true);
X509Certificate2 digitalID = collection[0];

//Load existing PDF document.
PdfLoadedDocument document = new PdfLoadedDocument("PDF_Succinctly.pdf");

//Load X509Certificate2.
PdfCertificate certificate = new PdfCertificate(digitalID);

//Create a revision 2 signature with loaded digital ID.
PdfSignature signature = new PdfSignature(document, document.Pages[0], certificate, "DigitalSignature");

//Changing the digital signature standard and hashing algorithm.
signature.Settings.CryptographicStandard = CryptographicStandard.CADES;
signature.Settings.DigestAlgorithm = DigestAlgorithm.SHA512;

//Save the PDF document.
document.Save("WindowsStore.pdf");

//Close the document.
document.Close(true);

}
}

By executing this code example, you will get a PDF document similar to the following screenshot.

PDF document digitally signed using Windows certificate store.
PDF document digitally signed using Windows certificate store.

Digitally sign a PDF document with an external signature

Let’s say your company needs to create a huge number of signed PDF documents. You cannot create them manually one by one. In this case, you need an automated solution, such as the ability to sign the documents in a server with your own HSM.

The PDF Library allows you to sign PDF documents with an external digital signature created from various sources such as HSM, USB tokens, and smart cards, or other cloud services such as DigiSign.

The following code example shows how to create a PDF digital signature in C# using an external signature.

using Syncfusion.Pdf.Parsing;
using Syncfusion.Pdf.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.Pkcs;
using System.Security.Cryptography.X509Certificates;

class Program
{
static void Main(string[] args)
{

//Load existing PDF document.
PdfLoadedDocument document = new PdfLoadedDocument("PDF_Succinctly.pdf");

//Create a revision 2 signature with loaded digital ID.
PdfSignature signature = new PdfSignature(document, document.Pages[0], null, "DigitalSignature");
signature.ComputeHash += Signature_ComputeHash;

//Save the PDF document.
document.Save("ExternalSignature.pdf");

//Close the document.
document.Close(true);

void Signature_ComputeHash(object sender, PdfSignatureEventArgs arguments)
{
//Get the document bytes.
byte[] documentBytes = arguments.Data;

SignedCms signedCms = new SignedCms(new ContentInfo(documentBytes), detached: true);
//Compute the signature using the specified digital ID file and the password.
X509Certificate2 certificate = new X509Certificate2("DigitalSignatureTest.pfx", "DigitalPass123");
var cmsSigner = new CmsSigner(certificate);
//Set the digest algorithm SHA256.
cmsSigner.DigestAlgorithm = new Oid("2.16.840.1.101.3.4.2.1");
signedCms.ComputeSignature(cmsSigner);
//Embed the encoded digital signature to the PDF document.
arguments.SignedData = signedCms.Encode();
}
}
}

By executing this code example, you will get a PDF document similar to the following screenshot.

PDF document digitally signed with external source.
PDF document digitally signed with external source.

Digitally sign existing signature field in a PDF document

You can load the signature field from an existing PDF document, and you can add the digital signature to it.

The following code example shows how to load an existing signature field and add a PDF digital signature in C#.

using Syncfusion.Pdf;
using Syncfusion.Pdf.Graphics;
using Syncfusion.Pdf.Parsing;
using Syncfusion.Pdf.Security;
class Program
{
static void Main(string[] args)
{
//Load existing PDF document.
PdfLoadedDocument document = new PdfLoadedDocument("PDF_SignField.pdf");

//Get the first page of the document.
PdfLoadedPage page = document.Pages[0] as PdfLoadedPage;

//Gets the first signature field from the PDF document.
PdfLoadedSignatureField field = document.Form.Fields[0] as PdfLoadedSignatureField;

//Load digital ID with password.
PdfCertificate certificate = new PdfCertificate("DigitalSignatureTest.pfx", "DigitalPass123");

field.Signature = new PdfSignature(document, page, certificate, "Signature", field);

//Get graphics from form field.
PdfGraphics graphics = field.Signature.Appearance.Normal.Graphics;
//Load image from file.
PdfImage image = PdfImage.FromFile("signature.png");
//Create a font to draw text.
PdfStandardFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 15);

//Draw text, shape, and image into the signature appearance.
graphics.DrawRectangle(PdfPens.Black, PdfBrushes.White, new System.Drawing.RectangleF(50, 0, field.Bounds.Width-50, field.Bounds.Height));
graphics.DrawImage(image, 0, 0, 100, field.Bounds.Height);
graphics.DrawString("Digitally Signed by Syncfusion", font, PdfBrushes.Black, 120, 17);
graphics.DrawString("Reason: Testing signature", font, PdfBrushes.Black, 120, 39);
graphics.DrawString("Location: USA", font, PdfBrushes.Black, 120, 60);

//Save the document.
document.Save("SignedField.pdf");
//Close the document.
document.Close(true);
}
}

To create a signature field, please refer to this UG documentation.

By executing this code example, you will get a PDF document similar to the following screenshot.

PDF digital signature included at the signature field.
PDF digital signature included at the signature field.

Add timestamp to the digital signature

A digital timestamp is used to create a PDF signature with a secure time and date as proof of integrity.

The following code example shows how to create a PDF digital signature in C# with a timestamp.

using Syncfusion.Pdf.Parsing;
using Syncfusion.Pdf.Security;
class Program
{
static void Main(string[] args)
{
//Load existing PDF document.
PdfLoadedDocument document = new PdfLoadedDocument("PDF_Succinctly.pdf");

//Load digital ID with password.
PdfCertificate certificate = new PdfCertificate(@"DigitalSignatureTest.pfx", "DigitalPass123");

//Create a signature with loaded digital ID.
PdfSignature signature = new PdfSignature(document, document.Pages[0], certificate, "DigitalSignature");

//Change the digital signature standard and hashing algorithm.
signature.Settings.CryptographicStandard = CryptographicStandard.CADES;
signature.Settings.DigestAlgorithm = DigestAlgorithm.SHA512;

//Add timestamp server link to the signature.
signature.TimeStampServer = new TimeStampServer(new Uri("http://timestamp.digicert.com/"));

//Save the PDF document.
document.Save("SignedTimestamp.pdf");

//Close the document.
document.Close(true);
}
}

By executing this code example, you will get a PDF document with the following information.

Time stamp details in the PDF digital signature.
Time stamp details in the PDF digital signature.

Retrieve digital signature information from an existing PDF document

Using the Syncfusion PDF Library, you can retrieve useful digital signature information, such as issuer name, validity, and digest algorithm, from an existing PDF document. You can then  display this information in your application.

The following code example shows how to retrieve digital signature information from an existing PDF document.

using Syncfusion.Pdf.Parsing;
using Syncfusion.Pdf.Security;
class Program
{
static void Main(string[] args)
{
//Load an existing PDF document.
PdfLoadedDocument document = new PdfLoadedDocument("SignedAppearance.pdf");

//Get the signature field from PdfLoadedDocument form field collection.
PdfLoadedSignatureField signatureField = document.Form.Fields[0] as PdfLoadedSignatureField;
PdfSignature signature = signatureField.Signature;

//Extract the signature information.
Console.WriteLine("Digitally Signed by: " + signature.Certificate.IssuerName);
Console.WriteLine("Valid From: " + signature.Certificate.ValidFrom);
Console.WriteLine("Valid To: " + signature.Certificate.ValidTo);
Console.WriteLine("Hash Algorithm : " + signature.Settings.DigestAlgorithm);
Console.WriteLine("Cryptographics Standard : " + signature.Settings.CryptographicStandard);

//Close the document.
document.Close(true);
}
}

Remove existing digital signatures from a PDF document

If you want to remove the existing contract and going to create a new one, you can remove the digital signatures from the existing PDF document and create a new one.

You can remove a digital signature from a PDF document using the following code example.

using Syncfusion.Pdf.Parsing;
class Program
{
static void Main(string[] args)
{
//Load an existing PDF document.
PdfLoadedDocument document = new PdfLoadedDocument("SignedAppearance.pdf");

//Get the signature field from PdfloadedDocument form field collection.
PdfLoadedSignatureField signatureField = document.Form.Fields[0] as PdfLoadedSignatureField;
//Remove signature field from PdfLoadedDocument form field collection.
document.Form.Fields.Remove(signatureField);

//Save the PDF document.
document.Save("RemoveDigital.pdf");
document.Close(true);
}
}

By executing this code example, you will get a PDF document like the following.

Digital signature removed from the PDF document.
Digital signature removed from the PDF document.

Validate PDF digital signature

To ensure the authenticity and integrity of a PDF document, you must validate the digital signature present in it. If you have a huge number of PDF documents, you cannot validate each document manually, so you need an automated solution.

The PDF Library has an API to validate digital signatures. You can validate them in any number of PDF documents without human interaction.

Digital signature validation takes the following steps to ensure validity:

  1. Validate the document modification.
  2. Validate the certificate chain.
  3. Ensure the signature with timestamp time.
  4. Check the revocation status of the certificate with OCSP and CRL.
  5. Ensure multiple digital signatures.

The following code example shows how to validate all the digital signatures present in a PDF document.

using Syncfusion.Pdf.Parsing;
using Syncfusion.Pdf.Security;
class Program
{
static void Main(string[] args)
{
//Load an existing PDF document.
PdfLoadedDocument document = new PdfLoadedDocument("MultipleSignature.pdf");
//Load PDF form.
PdfLoadedForm form = document.Form;

List results;

if (form != null)
{   

//Validate all the digital signatures present in the PDF document.
bool isvalid = form.Fields.ValidateSignatures(out results);

//Show the result based on the signature validation.
if (isvalid)
Console.WriteLine("All signatures are valid");
else
Console.WriteLine("At least one signature is invalid");

}

//Close the document.
document.Close(true);

}
}

The previous code example will iterate and validate all the digital signatures present in the PDF document. If any one of the digital signatures is invalid, then the result will be false. You can also get the validation results of the individual signatures.

The PdfSignatureValidationResult contains information about each digital signature and its status. We will see more details in upcoming topics.

Validate individual digital signatures in an existing PDF document

Syncfusion PDF Library allows you to iterate and validate individual digital signatures in an existing PDF document. The following code shows how to validate individual digital signatures.

using Syncfusion.Pdf.Parsing;
using Syncfusion.Pdf.Security;
class Program
{
static void Main(string[] args)
{
//Load an existing PDF document.
PdfLoadedDocument document = new PdfLoadedDocument("MultipleSignature.pdf");
//Load PDF form.
PdfLoadedForm form = document.Form;

if (form != null)
{
foreach (PdfLoadedField field in form.Fields)
{
if (field is PdfLoadedSignatureField)
{
PdfLoadedSignatureField signatureField = field as PdfLoadedSignatureField;

//Check whether the signature is signed.
if (signatureField.IsSigned)
{
//Validate the digital signature.
PdfSignatureValidationResult result = signatureField.ValidateSignature();

if (result.IsSignatureValid)
Console.WriteLine("Signature is valid");
else
Console.WriteLine("Signature is invalid");

//Retrieve the signature information.
Console.WriteLine("<<<<>>>>>>");
Console.WriteLine("Digitally Signed by: " + signatureField.Signature.Certificate.IssuerName);
Console.WriteLine("Valid From: " + signatureField.Signature.Certificate.ValidFrom);
Console.WriteLine("Valid To: " + signatureField.Signature.Certificate.ValidTo);
Console.WriteLine("Signature Algorithm : " + result.SignatureAlgorithm);
Console.WriteLine("Hash Algorithm : " + result.DigestAlgorithm);
Console.WriteLine("Cryptographics Standard : " + result.CryptographicStandard);
Console.Read();
}}}}}}

By executing this code example, you will get a PDF document with information similar to the following screenshot.

Validating PDF digital signatures.
Validating PDF digital signatures.

Validate signatures against a trusted list

You can create and pass your own list of trusted certificates to validate a digital signature in a PDF document.

The following example shows how to load a local Windows certificate store and validate the digital signature against it.

using Syncfusion.Pdf.Parsing;
using Syncfusion.Pdf.Security;
using System.Security.Cryptography.X509Certificates;
class Program
{
static void Main(string[] args)
{
//Load an existing PDF document.
PdfLoadedDocument document = new PdfLoadedDocument("MultipleSignature.pdf");
//Load PDF form.
PdfLoadedForm form = document.Form;

//Load Windows certificate store.
X509Store store = new X509Store("MY", StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
X509Certificate2Collection collection = (X509Certificate2Collection)store.Certificates;

if (form != null)
{
foreach (PdfLoadedField field in form.Fields)
{
if (field is PdfLoadedSignatureField)
{
PdfLoadedSignatureField signatureField = field as PdfLoadedSignatureField;

//Validate the digital signature against Windows certificate store.
PdfSignatureValidationResult result = signatureField.ValidateSignature(collection);

if (result.IsSignatureValid)
Console.WriteLine("Signature is valid");
else
Console.WriteLine("Signature is invalid");

//Update the signatures status based on the certificate validation against certificate store.
Console.WriteLine("Signature status: " + result.SignatureStatus);
}}}}}

Conclusion

In this blog post, we have walked through how to create and validate PDF digital signatures in C# using Syncfusion PDF Library. Now, you can easily include PDF digital signatures and validate them in your development process.

Take a moment to peruse our documentation, where you’ll find other options and features, all with accompanying code examples.

If you have any questions about these features, please let us know in the comments below. You can also contact us through our support forum, Direct-Trac, or feedback portal. We are happy to assist you!

If you liked this article, we think you would also like the following articles about PDF Library:

Tags:

Share this post:

Share on twitter
Share on facebook
Share on linkedin

Leave a comment

Popular Now

Be the first to get updates

Subscribe RSS feed
Scroll To Top