我需要使用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