我需要使用Windows证书存储中存在的证书签署PDF文档。我一直在挖掘一整天,试图找出它,而我如此接近而如此遥远。如何使用Windows Cert Store中的证书签署PDF文档?
所有缺少的是这样的:如何获得IExternalSignature对象以PDF文件签名?
Rahul Singla写的如何注册使用新的iText 5.3.0 API PDF文档一个美丽的例子 - 只要您可以访问.pfx文件在PC上坐着的地方。
使用来自Windows Cert Store的证书进行签名时有a previous question,只是它使用的是API版本,其中SetCrypto
仍存在,并且签名显然是可选的。在iText 5.3.0中,API已经改变,并且SetCrypto
不再是一件事情。
这里是我迄今(添加为后人评论,因为这可能是如何做到这一点的“网最全,最新版本):
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.security;
using BcX509 = Org.BouncyCastle.X509;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Crypto;
using DotNetUtils = Org.BouncyCastle.Security.DotNetUtilities;
...
// Set up the PDF IO
PdfReader reader = new PdfReader(@"some\dir\SomeTemplate.pdf");
PdfStamper stamper = PdfStamper.CreateSignature(reader,
new FileStream(@"some\dir\SignedPdf.pdf", FileMode.Create), '\0');
PdfSignatureAppearance sap = stamper.SignatureAppearance;
sap.Reason = "For no apparent raisin";
sap.Location = "...";
// Acquire certificate chain
var certStore = new X509Store(StoreName.My, StoreLocation.LocalMachine);
certStore.Open(OpenFlags.ReadOnly);
X509CertificateCollection certCollection =
certStore.Certificates.Find(X509FindType.FindBySubjectName,
"My.Cert.Subject", true);
X509Certificate cert = certCollection[0];
// iTextSharp needs this cert as a BouncyCastle X509 object; this converts it.
BcX509.X509Certificate bcCert = DotNetUtils.FromX509Certificate(cert);
var chain = new List<BcX509.X509Certificate> { bcCert };
certStore.Close();
// Ok, that's the certificate chain done. Now how do I get the PKS?
IExternalSignature signature = null; /* ??? */
// Sign the PDF file and finish up.
MakeSignature.SignDetached(sap, signature, chain, // the important stuff
null, null, null, 0, CryptoStandard.CMS);
stamper.Close();
正如你可以看到:我拥有除签名以外的所有东西,而我很难理解我应该如何获得它!
非常有用。谢谢! – 2014-05-19 11:10:24