I am trying to sign PDF file with USB token by using iTextSharp in C# and didn't get any success. If anybody have any solution which take the certificate from USB token and digitally signed PDF file in C#.
Asked
Active
Viewed 5,539 times
3
-
Please refer to SO answer https://stackoverflow.com/a/55676351/9659885 which provides working solution along with sample ASP.NET MVC projects – Bharat Vasant Aug 30 '19 at 10:18
1 Answers
4
Here is the code for getting the certificate:
X509CertificateParser cp = new X509CertificateParser();
//Get Sertifiacte
X509Certificate2 certClient = null;
X509Store st = new X509Store(StoreName.My, StoreLocation.CurrentUser);
st.Open(OpenFlags.MaxAllowed);
X509Certificate2Collection collection = X509Certificate2UI.SelectFromCollection(st.Certificates,
"Please choose certificate:", "", X509SelectionFlag.SingleSelection);
if (collection.Count > 0)
{
certClient = collection[0];
}
st.Close();
//Get Cert Chain
IList<X509Certificate> chain = new List<X509Certificate>();
X509Chain x509Chain = new X509Chain();
x509Chain.Build(certClient);
foreach (X509ChainElement x509ChainElement in x509Chain.ChainElements)
{
chain.Add(DotNetUtilities.FromX509Certificate(x509ChainElement.Certificate));
}
And here is my signing code:
PdfReader inputPdf = new PdfReader(fileInsert);
FileStream signedPdf = new FileStream(File_rename(fileInsert, "_signed"), FileMode.Create);
PdfStamper pdfStamper = PdfStamper.CreateSignature(inputPdf, signedPdf, '\0');
IExternalSignature externalSignature = new X509Certificate2Signature(certClient, "SHA-1");
PdfSignatureAppearance signatureAppearance = pdfStamper.SignatureAppearance;
//signatureAppearance.SignatureGraphic = Image.GetInstance(pathToSignatureImage);
//signatureAppearance.SetVisibleSignature(new iTextSharp.text.Rectangle(0, 00, 250, 150), inputPdf.NumberOfPages, "Signature");
signatureAppearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.DESCRIPTION;
MakeSignature.SignDetached(signatureAppearance, externalSignature, chain, null, null, null, 0,
CryptoStandard.CMS);
inputPdf.Close();
pdfStamper.Close();
fileinsert is the file name you want to be signed and
File_rename(fileInsert, "_signed")
is a method that renames the original file name like "noname.pdf" to "noname_signed.pdf".
And the libraries used:
using Org.BouncyCastle.Security;
using Org.BouncyCastle.X509;
using System.Security.Cryptography.X509Certificates;
using X509Certificate = Org.BouncyCastle.X509.X509Certificate;
I hope it helps, I wrote the code some years ago using some examples I found searching forums, but I still use it sometimes.
Razvan
- 80
- 8
-
-
1
-
In case you experience an exception: "pdf header signature not found" - the reason was that I used as the input a memory stream in the line PdfReader inputPdf = new PdfReader(myMemoryStream); and needed to set the myMemoryStream.Position = 0; before that – Vladimír Hála Mar 13 '23 at 11:42