enter image description hereI have SignedHash and certificate to sign the pdf file. The Signedhash and Certificate both received through external services. How to embed SignedHash to the PDF and then verify it with certificate using C#?
// Here we are using Itextsharp
public static void SignDoc(string inputFilePath, string outputFilePath)
{
// Open pdf
using (PdfReader reader = new PdfReader(inputFilePath))
{
using (MemoryStream ms = new MemoryStream())
{
//Code to add new sig appearance
BaseFont helvetica = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.EMBEDDED);
Font font = new Font(helvetica, 12, iTextSharp.text.Font.NORMAL);
PdfStamper stamper = PdfStamper.CreateSignature(reader, ms, '\0');
PdfSignatureAppearance sap = stamper.SignatureAppearance;
sap.Reason = "";
sap.Location = "";
sap.Contact = "";
sap.Layer2Font = font;
// Setting up Visible Sig
sap.SetVisibleSignature(new iTextSharp.text.Rectangle(415, 100, 585, 40), 1, null);
var dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED);
dic.Reason = sap.Reason;
dic.Location = sap.Location;
dic.Contact = sap.Contact;
dic.Date = new PdfDate(sap.SignDate);
sap.CryptoDictionary = dic;
Dictionary<PdfName, int> exc = new Dictionary<PdfName, int>();
exc.Add(PdfName.CONTENTS, (int)(8192 * 2 + 2));
sap.PreClose(exc);
Stream data = sap.GetRangeStream();
//Extract the bytes that need to be signed
// Creating hash of pdf with signature appearance
byte[] hash = DigestAlgorithms.Digest(data, DigestAlgorithms.SHA256);
// Calling third party digidenty service for Cert as well as SignHash
var signedDocResp = SignUtility.GetSignHashAndCertificate(BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant());
X509Certificate2 cert2 = new X509Certificate2(Encoding.Unicode.GetBytes(signedDocResp.Certificate));
var cert = new Org.BouncyCastle.X509.X509CertificateParser().ReadCertificate(cert2.GetRawCertData());
var chain = new List<Org.BouncyCastle.X509.X509Certificate>() { cert };
PdfPKCS7 sgn = new PdfPKCS7(null, chain, DigestAlgorithms.SHA256, false);
byte[] sh = sgn.getAuthenticatedAttributeBytes(Encoding.Unicode.GetBytes(signedDocResp.SignedHash), null, null, CryptoStandard.CMS);
sgn.SetExternalDigest(Encoding.Unicode.GetBytes(signedDocResp.SignedHash), null, "RSA");
byte[] encodedSig = sgn.GetEncodedPKCS7(sh, null, null, null, CryptoStandard.CMS);
byte[] paddedSig = new byte[8192];
encodedSig.CopyTo(paddedSig, 0);
PdfDictionary dic2 = new PdfDictionary();
dic2.Put(PdfName.CONTENTS, new PdfString(paddedSig).SetHexWriting(true));
sap.Close(dic2);
byte[] signed = ms.ToArray();
File.WriteAllBytes(outputFilePath, signed);
}
}
}