Adding a Digital Signature to a PDF Using a PFX File And iTextSharp in C#

Introduction

Adding a digital signature to a PDF is like giving it a special digital stamp that ensures it's real, safe, and from the right person. In this article, we'll learn how to put a digital stamp on a PDF using iTextSharp in C#. This helps make sure your digital papers are real and trustworthy.

Step 1. Create a project and install the library

Create a new C# project in your preferred development environment and  Install the iTextSharp library using NuGet to enable PDF manipulation.

Step 2. Loading the PDF Document

Import necessary namespaces.

using System;
using System.IO;
using System.Linq;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.security;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Pkcs;

Load the PDF document that you want to sign using PdfReader.

string pdfFilePath = "C:\\Users\\Admin\\Documents\\MyPDF.pdf";
PdfReader pdfReader = new PdfReader(pdfFilePath);

Step 3. Loading the Digital Certificate

Load the PFX certificate file that contains your digital signature and also give the password for your digital signature.

string pfxFilePath = "D:\\Uday Dodiya\\Digital_Sign\\Uday Dodiya.pfx";
string pfxPassword = "uday1234";
Pkcs12Store pfxKeyStore = new Pkcs12Store(new FileStream(pfxFilePath, FileMode.Open, FileAccess.Read), pfxPassword.ToCharArray());

Step 4. Initialize the PDF Stamper And Create the Signature Appearance

We'll initialize a PdfStamper object, which allows us to add content to the PDF.

PdfStamper pdfStamper = PdfStamper.CreateSignature(pdfReader, new FileStream("C:\\Users\\Admin\\Documents\\MyPDF_Signed.pdf", FileMode.Create), '\0', null, true);

To set up the appearance of the digital signature, we'll use the PdfSignatureAppearance class. You can set the x and y positions according to your requirements.

PdfSignatureAppearance signatureAppearance = pdfStamper.SignatureAppearance;
signatureAppearance.Reason = "Digital Signature Reason";
signatureAppearance.Location = "Digital Signature Location";

// Set the signature appearance location (in points)
float x = 360;
float y = 130;
signatureAppearance.Acro6Layers = false;
signatureAppearance.Layer4Text = PdfSignatureAppearance.questionMark;
signatureAppearance.SetVisibleSignature(new iTextSharp.text.Rectangle(x, y, x + 150, y + 50), 1, "signature");

Step 5. Adding the Digital Signature

Set the visible signature area on the PDF page.

Use the private key to create the digital signature.

Embed the signature into the PDF using MakeSignature.SignDetached.

string alias = pfxKeyStore.Aliases.Cast<string>().FirstOrDefault(entryAlias => pfxKeyStore.IsKeyEntry(entryAlias));

if (alias != null)
{
      ICipherParameters privateKey = pfxKeyStore.GetKey(alias).Key;
      IExternalSignature pks = new PrivateKeySignature(privateKey, DigestAlgorithms.SHA256);
      MakeSignature.SignDetached(signatureAppearance, pks, new 
      Org.BouncyCastle.X509.X509Certificate[] { pfxKeyStore.GetCertificate(alias).Certificate }, 
      null, null, null, 0, CryptoStandard.CMS);
}
else
{
      Console.WriteLine("Private key not found in the PFX certificate.");
}

Step 6. Saving the Signed PDF

Close the PdfStamper to save the modified PDF with the added signature

pdfStamper.Close();

Full Code

using System;
using System.IO;
using System.Linq;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.security;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Pkcs;

namespace DigitalSignPDF
{
    class Program
    {
        static void Main(string[] args)
        {
            // Step 2: Load PDF Document
            string pdfFilePath = "C:\\Users\\Admin\\Documents\\MyPDF.pdf";
            PdfReader pdfReader = new PdfReader(pdfFilePath);

            // Step 3: Load PFX Certificate
            string pfxFilePath = "D:\\Uday Dodiya\\Digital_Sign\\Uday Dodiya.pfx";
            string pfxPassword = "uday1234";
            Pkcs12Store pfxKeyStore = new Pkcs12Store(new FileStream(pfxFilePath, FileMode.Open, FileAccess.Read), pfxPassword.ToCharArray());

            // Step 4: Initialize the PDF Stamper And Creating the Signature Appearance
            PdfStamper pdfStamper = PdfStamper.CreateSignature(pdfReader, new FileStream("C:\\Users\\Admin\\Documents\\MyPDF_Signed.pdf", FileMode.Create), '\0', null, true);
            PdfSignatureAppearance signatureAppearance = pdfStamper.SignatureAppearance;
            signatureAppearance.Reason = "Digital Signature Reason";
            signatureAppearance.Location = "Digital Signature Location";

            // Set the signature appearance location (in points)
            float x = 360;
            float y = 130;
            signatureAppearance.Acro6Layers = false;
            signatureAppearance.Layer4Text = PdfSignatureAppearance.questionMark;
            signatureAppearance.SetVisibleSignature(new iTextSharp.text.Rectangle(x, y, x + 150, y + 50), 1, "signature");

            // Step 5: Sign the Document
            string alias = pfxKeyStore.Aliases.Cast<string>().FirstOrDefault(entryAlias => pfxKeyStore.IsKeyEntry(entryAlias));

            if (alias != null)
            {
                ICipherParameters privateKey = pfxKeyStore.GetKey(alias).Key;
                IExternalSignature pks = new PrivateKeySignature(privateKey, DigestAlgorithms.SHA256);
                MakeSignature.SignDetached(signatureAppearance, pks, new Org.BouncyCastle.X509.X509Certificate[] { pfxKeyStore.GetCertificate(alias).Certificate }, null, null, null, 0, CryptoStandard.CMS);
            }
            else
            {
                Console.WriteLine("Private key not found in the PFX certificate.");
            }

            // Step 6: Save the Signed PDF
            pdfStamper.Close();

            Console.WriteLine("PDF signed successfully!");
        }
    }
}

Output

Console Window

output

Original PDF File (MyPDF.pdf)

Original PDF

Signed PDF File (MyPDF_Signed.pdf)

Signed PDF

Add a Digital Signature to Multiple Pages of a PDF Using PFX File And iTextSharp in C#

To add a digital signature to all pages of a PDF using iTextSharp in C#, you need to loop through each page of the PDF and apply the digital signature to each page. Here's how you can modify your code to achieve this.

using System;
using System.IO;
using System.Linq;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.security;
using Microsoft.VisualBasic;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Pkcs;

namespace DigitalSignPDF
{
    class Program
    {
        static void Main(string[] args)
        {
            // Step 2: Load PDF Document
            string pdfFilePath = "C:\\Users\\Admin\\Documents\\MyPDF1.pdf";
            string destinationPath = "C:\\Users\\Admin\\Documents\\MyPDF_Signed1.pdf";
            PdfReader pdfReader = new PdfReader(pdfFilePath);

            // Step 3: Load PFX Certificate
            string pfxFilePath = "D:\\Uday Dodiya\\Digital_Sign\\Uday Dodiya.pfx";
            string pfxPassword = "uday1234";
            Pkcs12Store pfxKeyStore = new Pkcs12Store(new FileStream(pfxFilePath, FileMode.Open, FileAccess.Read), pfxPassword.ToCharArray());

            // Step 4: Count the pages and add signature in each page
            int page = pdfReader.NumberOfPages;
            for(int  i=1; i<=page; i++)
            {
                if(i > 1)
                {
                    FileStream stremfile = new FileStream(destinationPath, FileMode.Open, FileAccess.Read);
                    pdfReader = new PdfReader(stremfile);
                    File.Delete(destinationPath);
                }
                
                // Step 4.1: Initialize the PDF Stamper And Creating the Signature Appearance
                FileStream signedPdf = new FileStream(destinationPath, FileMode.Create, FileAccess.ReadWrite);
                PdfStamper pdfStamper = PdfStamper.CreateSignature(pdfReader, signedPdf, '\0', null, true);
                PdfSignatureAppearance signatureAppearance = pdfStamper.SignatureAppearance;

                signatureAppearance.Reason = "Digital Signature Reason";
                signatureAppearance.Location = "Digital Signature Location";
                signatureAppearance.Acro6Layers = false;

                // Set the signature appearance location (in points)
                float x = 360;
                float y = 130;
                signatureAppearance.Acro6Layers = false;
                signatureAppearance.Layer4Text = PdfSignatureAppearance.questionMark;
                signatureAppearance.SetVisibleSignature(new iTextSharp.text.Rectangle(x, y, x + 150, y + 50), i, null);


                // Step 4.2: Sign the Document
                string alias = pfxKeyStore.Aliases.Cast<string>().FirstOrDefault(entryAlias => pfxKeyStore.IsKeyEntry(entryAlias));
                ICipherParameters privateKey = pfxKeyStore.GetKey(alias).Key;
                IExternalSignature pks = new PrivateKeySignature(privateKey, DigestAlgorithms.SHA256);

                MakeSignature.SignDetached(signatureAppearance, pks, new Org.BouncyCastle.X509.X509Certificate[] { pfxKeyStore.GetCertificate(alias).Certificate }, null, null, null, 0, CryptoStandard.CMS);

                // Step 4.3: Save the Signed PDF
                pdfReader.Close();
                pdfStamper.Close();
            }
            Console.WriteLine("PDF signed successfully!");
        }
    }
}

Summary

So you see, adding a digital signature to a PDF is very easy.

In this article, we will learn How to add a digital signature to your PDF using iTextSharp in C#.

If you like my article, please like it and comment with your views on it.

Thank you. Enjoy Coding.


Similar Articles