Digital signature of PDF by using .pfx File

Digital signature of PDF file by using .pfx file C# with Itextsharp library
For Development I have used VS 2015
Required
You will have to digital signature token or .pfx file issued by government.

Get Information about DSC Token and .pfx file Click on DSC Token Info


Here complete code in console application using c#
First add "Itextsharp.dll" file from NewGet package manager and add reference.

Complete Code are -

using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.security;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Security;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace DigitalSignConsole
{
    class SignPDFUsingPFX
    {
        static void Main(string[] args)
        {
            int num = 0;
            string text = "";
            string text2 = "";
            int num2 = 0;
            string FilePath = @"E:/DigitalSignature/invoice/";
            string SignFilePath = @"E:/DigitalSignature/Signinvoice/";

            string[] files = Directory.GetFiles(FilePath);
            DirectoryInfo dir = new DirectoryInfo(FilePath);

            foreach (FileInfo flInfo in dir.GetFiles())
            {
                string text3 = "", SignPdfName = "";
                text3 = flInfo.Name;
                string path = "OldFilePath:" + flInfo.DirectoryName + "\\" + text3 + "$";
                SignPdfName = "NewFilePath:" + SignFilePath + text3 + "$";

                text = getBetween(path, "OldFilePath:", "$");
                text2 = getBetween(SignPdfName, "NewFilePath:", "$");

            }
            using (MemoryStream ms = new MemoryStream())
            {
                PdfCopyFields copy = new PdfCopyFields(ms);
                copy.Writer.ViewerPreferences = PdfWriter.PageModeUseOutlines;
                ArrayList outlines = new ArrayList();
                int pageOffset = 0;
                string file = text;
                PdfReader reader = new PdfReader(file);
                copy.AddDocument(reader);
                pageOffset += reader.NumberOfPages;
                copy.Close();
                reader.Close();
                System.GC.Collect();
                System.GC.WaitForPendingFinalizers();
                MemoryStreamToFile(ms, text);
            }

            //Certificate part start here

            string pathToCert = @"E:\DigitalSignature\local.pfx";
            string passCert = "shashi";
            var pass = passCert.ToCharArray();

            FileStream fs;
            try
            {
                fs = new FileStream(pathToCert, FileMode.Open);
            }
            catch (Exception ex)
            {
                return;
            }
            var store = new Pkcs12Store(fs, pass);
            fs.Close();
            var alias = "";

            // searching for private key
            foreach (string al in store.Aliases)
                if (store.IsKeyEntry(al) && store.GetKey(al).Key.IsPrivate)
                {
                    alias = al;
                    break;
                }

            var pk = store.GetKey(alias);
           
            ICollection<Org.BouncyCastle.X509.X509Certificate> chain = store.GetCertificateChain(alias).Select(c => c.Certificate).ToList();
            var parameters = pk.Key as RsaPrivateCrtKeyParameters;

            PdfReader pdfReader = new PdfReader(text);
            num2 = pdfReader.NumberOfPages;
            pdfReader.Close();
            Console.WriteLine("Signing file...");
            for (int i = 1; i <= num2; i++)
            {
                if (i != 1)
                {
                    File.Delete(text);
                    File.Copy(text2, text);
                    File.Delete(text2);
                }
                PdfReader pdfReader2 = new PdfReader(text);
                FileStream fileStream = new FileStream(text2, FileMode.Create);

                PdfStamper pdfStamper = PdfStamper.CreateSignature(pdfReader2, fileStream, '\0', Path.GetTempFileName(), append: true);
                PdfSignatureAppearance signatureAppearance = pdfStamper.SignatureAppearance;
                signatureAppearance.Acro6Layers = false;
                signatureAppearance.Reason = "Digitily Sign Invoice";
                signatureAppearance.Location = "Testing";
                signatureAppearance.SignDate = DateTime.Now;

              //signatureAppearance.Layer2Text=("Digitally signed by " + "Shashi" + "\n\nDate: " + DateTime.Now);     //set manually signing authority

                signatureAppearance.SetVisibleSignature(new Rectangle(600f, 55f, 450f, 90f), i, null);

                // appearance.SetVisibleSignature("---> ExistSignatureName <-----");                
                 signatureAppearance.SetVisibleSignature(new Rectangle(600f, 55f, 450f, 90f), i, null);

                IExternalSignature pks = new PrivateKeySignature(parameters, DigestAlgorithms.SHA256);
                MakeSignature.SignDetached(signatureAppearance, pks, chain, null, null, null, 0, CryptoStandard.CMS);

                fileStream.Close();
                pdfReader2.Close();
                pdfStamper.Close();


            }
            File.Delete(text);

        }

        // CertSelect
        public static string getBetween(string strSource, string strStart, string strEnd)
        {
            if (strSource.Contains(strStart) && strSource.Contains(strEnd))
            {
                int num = strSource.IndexOf(strStart, 0) + strStart.Length;
                int num2 = strSource.IndexOf(strEnd, num);
                return strSource.Substring(num, num2 - num);
            }
            return "";
        }

        public static void MemoryStreamToFile(MemoryStream MS, string FileName)
        {
            using (FileStream fs = new FileStream(@FileName, FileMode.Create))
            {
                byte[] data = MS.ToArray();
                fs.Write(data, 0, data.Length);
                fs.Close();
            }
        }
    }
}

Leave a Comment