如何使用Windows Cert Store中的证书签署PDF文档?

dop*_*ner 9 c# pdf signing certificate itextsharp

我需要使用Windows证书库中存在的证书来签署PDF文档.我一直在周围挖了一整天试图弄明白,我那么近那么远.

所有缺少的是:如何获取IExternalSignature对象来签署PDF文件?

Rahul Singla写了一个很好的例子,说明如何使用新的iText 5.3.0 API签署PDF文档 - 只要你可以在某个地方访问PC上的.pfx文件.

一个关于使用Windows证书存储区中的证书进行签名的问题,除了它使用的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();
Run Code Online (Sandbox Code Playgroud)

正如你所看到的:除了签名之外我什么都有,而且我很难知道如何获得它!

Sam*_*les 3

X509Certificate cert = certCollection[0]; // Your code
X509Certificate2 signatureCert = new X509Certificate2(cert);

var pk = Org.BouncyCastle.Security.DotNetUtilities.GetKeyPair(signatureCert.PrivateKey).Private;
Run Code Online (Sandbox Code Playgroud)

如果您有 pk(可以如上获取),则可以按如下方式创建 IExternalSignature:

IExternalSignature es = new PrivateKeySignature(pk, "SHA-256");
Run Code Online (Sandbox Code Playgroud)

您还可以找到以下使用文章: