我需要使用 Windows 证书存储中存在的证书签署 PDF 文档。我整天都在挖,想弄明白,我离得那么近,却又那么远。
所缺少的只是:如何获得一个 IExternalSignature 对象来签署 PDF 文件?
Rahul Singla编写了一个漂亮的示例,说明如何使用新的 iText 5.3.0 API 对 PDF 文档进行签名 -只要您可以访问 PC 上某处的 .pfx 文件。
之前有一个关于使用 Windows Cert Store 中的证书进行签名的问题,除了它使用的 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();
如您所见:除了签名之外,我什么都有,但我不知道应该如何获得它!