Devo firmare un documento PDF utilizzando un certificato presente nell'archivio certificati di Windows. Sto scavando tutto il giorno cercando di capirlo, e io sono così vicino ancora così lontano.Come si firma un documento PDF utilizzando un certificato da Windows Cert Store?
Tutto ciò che manca è questo: Come si ottiene un oggetto IExternalSignature con cui firmare il file PDF?
Rahul Singla ha scritto un bellissimo esempio di come firmare un documento PDF utilizzando la nuova API iText 5.3.0 - finché è possibile accedere a un file pfx seduti intorno sul vostro PC da qualche parte.
C'è a previous question alla firma utilizzando un certificato da Windows Cert Store, tranne che utilizzava una versione dell'API in cui esiste ancora SetCrypto
e la firma apparentemente era facoltativa. In iText 5.3.0, l'API è cambiata e SetCrypto
non è più un problema.
Ecco quello che ho finora (i commenti aggiunti per i posteri, dal momento che questo potrebbe essere la versione più completa e recente di come fare questo 'sulla rete):
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();
Come si può vedere: Ho tutto tranne la firma, e sono perplesso su come dovrei ottenerlo!
Molto utile. Grazie! –