I’m sharing the code with you as I’m unable attach a project.
Note: For security reasons, I have removed the InputFilePath,OutputFilePath ,PFX file store and its password from the shared project.
using iText.Kernel.Pdf;
using iText.Signatures;
using itextpdf.kernel.pdf.canvas.parser;
using itextpdf.kernel.pdf.canvas.parse.Listener;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.X509;
using System.IO;
using iText.Bouncycastle.Cert;
using iText.Bouncycastle.X509;
using iText.Bouncycastle.Crypto;
using iText.Commons.Bouncycastle.Cert;
using iText.IO.Font.Constants;
using iText.Kernel.Font;
using iText.Kernel.Geom;
using iText.Kernel.Pdf;
PdfReader reader1=new PdfReader(input);
PdfDocument pdfDocument = new PdfDocument(reader1);
IExternalSignature _privateSignature;
IX509Certificate _signChain;
string KEYSTORE = @“”;
char PASSWORD = “”.ToCharArray();
(I am receving error for below line)
var pks = new Org.BouncyCastle.Pkcs.Pkcs12Store(new FileStream(KEYSTORE,FileMode.Open, FileAccess.Read), PASSWORD);
string alias = null;
foreach (string tAlias in pks.Aliases)
{
if (pks.IsKeyEntry(tAlias))
{
alias = tAlias;break;
}
}
var pk = pks.GetKey(alias).Key;
var ce = pks.GetCertificateChain(alias);
_signChain = new IX509Certificate[ce.Length];
for (int k = 0; k< ce.Length; ++k)
_signChain[k] = new X509CertificateBC(ce[k].Certificate);
_privateSignature = new PrivateKeySignature(new PrivateKeyBC(pk), “SHA-512”);
using (FileStream signedPdf = new FileStream(output, FileMode.Create, FileAccess.ReadWrite))
{
StampingProperties properties = new StampingProperties();
var signer = new iText.Signatures.PdfSigner(pdfReader, signedPdf, properties.UseAppendMode());
PdfSignatureAppearance sap = signer.GetSignatureAppearance();
sap.SetLayer2Text(string.Empty);
sap.SetPageNumber(pageNumber);
sap.SetLayer2Text(DateTime.Now.ToString());
sap.SetRenderingMode(PdfSignatureAppearance.RenderingMode.NAME_AND_DESCRIPTION);
sap.SetLayer2FontSize(7);
sap.SetPageRect(new iText.Kernel.Geom.Rectangle(50, 700, 200, 100));
PdfFont font = PdfFontFactory.CreateFont(StandardFonts.HELVETICA);
sap.SetLayer2Font(font);
signer.SignDetached(_privateSignature, _signChain, null, null, null, 0, iText.Signatures.PdfSigner.CryptoStandard.CMS);
}`