static void Main(string[] args) { PdfDocument doc = new PdfDocument(@"..\..\test.pdf"); PdfCertificate cert = new PdfCertificate(@"..\..\Demo.pfx", "e-iceblue"); var signature = new PdfSignature(doc, doc.Pages[0], cert, "Requestd1"); signature.Bounds = new RectangleF(new PointF(280, 600), new SizeF(260, 90)); signature.IsTag = true; signature.DigitalSignerLable = "Digitally signed by"; signature.DigitalSigner = "Harry Hu for Test"; signature.DistinguishedName = "DN:"; signature.LocationInfoLabel = "Location:"; signature.LocationInfo = "London"; signature.ReasonLabel = "Reason: "; signature.Reason = "Le document est certifie"; signature.DateLabel = "Date: "; signature.Date = DateTime.Now; signature.ContactInfoLabel = "Contact: "; signature.ContactInfo = "123456789"; signature.Certificated = false; signature.ConfigGraphicType = ConfiguerGraphicType.Picture; signature.ConfiguerGraphicPath = "..\\..\\img1.png"; signature.DocumentPermissions = PdfCertificationFlags.ForbidChanges; doc.SaveToFile(@"..\..\sample.pdf"); System.Diagnostics.Process.Start(@"..\..\sample.pdf"); }
private void button1_Click(object sender, EventArgs e) { //Create a pdf document. PdfNewDocument doc = new PdfNewDocument(); // Create one page PdfPageBase page = doc.Pages.Add(); //Draw the page DrawPage(page); String pfxPath = @"..\..\..\..\..\..\Data\Demo.pfx"; PdfCertificate cert = new PdfCertificate(pfxPath, "e-iceblue"); PdfSignature signature = new PdfSignature(doc, page, cert, "demo"); signature.ContactInfo = "Harry Hu"; signature.Certificated = true; signature.DocumentPermissions = PdfCertificationFlags.AllowFormFill; //Save pdf file. doc.Save("DigitalSignature.pdf"); doc.Close(); //Launching the Pdf file. PDFDocumentViewer("DigitalSignature.pdf"); }
static void Main(string[] args) { using (PdfDocumentProcessor documentProcessor = new PdfDocumentProcessor()) { documentProcessor.LoadDocument(@"..\..\Document.pdf"); X509Certificate2 certificate = new X509Certificate2(@"..\..\SignDemo.pfx", "dxdemo"); byte[] imageData = File.ReadAllBytes("..\\..\\image.emf"); int pageNumber = 1; int angleInDegrees = 45; double angleInRadians = angleInDegrees * (Math.PI / 180); PdfOrientedRectangle signatureBounds = new PdfOrientedRectangle(new PdfPoint(620, 210), 250, 90, angleInRadians); PdfSignature signature = new PdfSignature(certificate, imageData, pageNumber, signatureBounds); signature.Location = "USA"; signature.ContactInfo = "*****@*****.**"; signature.Reason = "Approved"; documentProcessor.SaveDocument(@"..\..\SignedDocument.pdf", new PdfSaveOptions() { Signature = signature }); } }
/** * Signs a document with a PAdES-LTV Timestamp. The document is closed at the end. * @param sap the signature appearance * @param tsa the timestamp generator * @param signatureName the signature name or null to have a name generated * automatically * @throws Exception */ public static void Timestamp(PdfSignatureAppearance sap, ITSAClient tsa, String signatureName) { int contentEstimated = tsa.GetTokenSizeEstimate(); sap.SetVisibleSignature(new Rectangle(0,0,0,0), 1, signatureName); PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ETSI_RFC3161); dic.Put(PdfName.TYPE, PdfName.DOCTIMESTAMP); sap.CryptoDictionary = dic; Dictionary<PdfName,int> exc = new Dictionary<PdfName,int>(); exc[PdfName.CONTENTS] = contentEstimated * 2 + 2; sap.PreClose(exc); Stream data = sap.GetRangeStream(); IDigest messageDigest = DigestUtilities.GetDigest(tsa.GetDigestAlgorithm()); byte[] buf = new byte[4096]; int n; while ((n = data.Read(buf, 0, buf.Length)) > 0) { messageDigest.BlockUpdate(buf, 0, n); } byte[] tsImprint = new byte[messageDigest.GetDigestSize()]; messageDigest.DoFinal(tsImprint, 0); byte[] tsToken = tsa.GetTimeStampToken(tsImprint); if (contentEstimated + 2 < tsToken.Length) throw new Exception("Not enough space"); byte[] paddedSig = new byte[contentEstimated]; System.Array.Copy(tsToken, 0, paddedSig, 0, tsToken.Length); PdfDictionary dic2 = new PdfDictionary(); dic2.Put(PdfName.CONTENTS, new PdfString(paddedSig).SetHexWriting(true)); sap.Close(dic2); }
static void Main(string[] args) { //Create a pdf document. PdfDocument doc = new PdfDocument(); doc.AppendPage(); //doc.SaveToFile("../../testingC.pdf"); //doc.LoadFromFile("../../testingC.pdf"); var page = doc.Pages[0]; String pfxPath = @"../../test.pfx"; PdfCertificate cert = new PdfCertificate(pfxPath, "123456"); PdfSignature signature = new PdfSignature(doc, page, cert, "signname") { ContactInfo = "contact", Certificated = true, DocumentPermissions = PdfCertificationFlags.AllowFormFill, Location = new System.Drawing.PointF(50, 50), LocationInfo = "center" }; //Save pdf file. doc.SaveToFile(@"../../testingC signed.pdf"); doc.Close(); }
private void button1_Click(object sender, EventArgs e) { //Create a pdf document. PdfNewDocument doc = new PdfNewDocument(); // Create one page PdfPageBase page = doc.Pages.Add(); //Draw the page DrawPage(page); String pfxPath = @"..\..\..\..\..\..\Data\Demo.pfx"; PdfCertificate cert = new PdfCertificate(pfxPath, "e-iceblue"); PdfSignature signature = new PdfSignature(doc, page, cert, "demo"); signature.ContactInfo = "Harry Hu"; signature.Certificated = true; signature.DocumentPermissions = PdfCertificationFlags.AllowFormFill; //Save pdf file. doc.Save("DigitalSignature.pdf"); doc.Close(); //Launching the Pdf file. PDFDocumentViewer("DigitalSignature.pdf"); }
public static void Main() { // NOTE: // When used in trial mode, the library imposes some restrictions. // Please visit http://bitmiracle.com/pdf-library/trial-restrictions.aspx // for more information. StringBuilder sb = new StringBuilder(); using (PdfDocument pdf = new PdfDocument(@"..\Sample Data\signed.pdf")) { PdfControl field = pdf.GetControls().FirstOrDefault(c => c.Type == PdfWidgetType.Signature); if (field == null) { Console.WriteLine("Document does not contain signature fields"); return; } PdfSignature signature = ((PdfSignatureField)field).Signature; PdfSignatureContents contents = signature.Contents; sb.AppendFormat("Signed part is intact: {0}\n", contents.VerifyDigest()); DateTime signingTime = signature.SigningTime ?? DateTime.MinValue; sb.AppendFormat("Signed on: {0}\n", signingTime.ToShortDateString()); var timestampToken = contents.GetTimestampToken(); if (timestampToken != null) { sb.AppendFormat("Embedded timestamp: {0}\n", timestampToken.GenerationTime); if (timestampToken.TimestampAuthority != null) { sb.AppendFormat("Timestamp authority: {0}\n", timestampToken.TimestampAuthority.Name); } sb.AppendFormat("Timestamp is intact: {0}\n\n", contents.VerifyTimestamp()); } else { sb.AppendLine(); } if (contents.CheckHasEmbeddedOcsp()) { sb.AppendLine("Signature has OCSP embedded."); checkRevocation(signature, sb, PdfCertificateRevocationCheckMode.EmbeddedOcsp); } if (contents.CheckHasEmbeddedCrl()) { sb.AppendLine("Signature has CRL embedded."); checkRevocation(signature, sb, PdfCertificateRevocationCheckMode.EmbeddedCrl); } checkRevocation(signature, sb, PdfCertificateRevocationCheckMode.OnlineOcsp); checkRevocation(signature, sb, PdfCertificateRevocationCheckMode.OnlineCrl); } Console.WriteLine(sb.ToString()); }
public static void Main() { // NOTE: // When used in trial mode, the library imposes some restrictions. // Please visit http://bitmiracle.com/pdf-library/trial-restrictions.aspx // for more information. StringBuilder sb = new StringBuilder(); using (PdfDocument pdf = new PdfDocument(@"..\Sample Data\signed.pdf")) { PdfControl control = pdf.GetControls().FirstOrDefault(c => c.Type == PdfWidgetType.Signature); if (control == null) { Console.WriteLine("Document does not contain signature fields"); return; } PdfSignatureField field = (PdfSignatureField)control; sb.AppendFormat("Signature field is invisible: {0}\n", isInvisible(field)); PdfSignature signature = field.Signature; sb.AppendFormat("Signed by: {0}\n", signature.Name); sb.AppendFormat("Signing time: {0}\n", signature.SigningTime); sb.AppendFormat("Signed at: {0}\n", signature.Location); sb.AppendFormat("Reason for signing: {0}\n", signature.Reason); sb.AppendFormat("Signer's contact: {0}\n", signature.ContactInfo); PdfSignatureContents contents = signature.Contents; sb.AppendFormat("Has OCSP embedded: {0}\n", contents.CheckHasEmbeddedOcsp()); sb.AppendFormat("Has CRL embedded: {0}\n", contents.CheckHasEmbeddedCrl()); PdfSignatureCertificate certificate = contents.GetSigningCertificate(); sb.AppendLine(); sb.AppendLine("== Signing certificate:"); sb.AppendFormat("Name: {0}\n", certificate.Name); sb.AppendFormat("Algorithm: {0}\n", certificate.AlgorithmName); sb.AppendFormat("Subject DN: {0}\n", certificate.Subject.Name); sb.AppendFormat("Issuer DN: {0}\n", certificate.Issuer.Name); sb.AppendFormat("Serial number: {0}\n", certificate.SerialNumber); sb.AppendFormat("Valid from {0} up to {1}\n", certificate.ValidFrom, certificate.ValidUpto); sb.AppendFormat("Timestamp Authority URL: {0}\n", certificate.GetTimestampAuthorityUrl()); PdfSignatureCertificate issuer = contents.GetIssuerCertificateFor(certificate); sb.AppendLine(); sb.AppendLine("== Issuer certificate:"); sb.AppendFormat("Subject DN: {0}\n", issuer.Subject.Name); sb.AppendFormat("Issuer DN: {0}\n", issuer.Issuer.Name); sb.AppendFormat("Serial number: {0}\n", issuer.SerialNumber); } Console.WriteLine(sb.ToString()); }
private void button1_Click(object sender, EventArgs e) { OpenFileDialog dialog = new OpenFileDialog(); dialog.Filter = "PDF document (*.pdf)|*.pdf"; DialogResult result = dialog.ShowDialog(); if (result == DialogResult.OK) { try { string pdfFile = dialog.FileName; List <PdfSignature> signatures = new List <PdfSignature>(); //Open a pdf document and get its all signatures using (PdfDocument pdf = new PdfDocument()) { pdf.LoadFromFile(pdfFile); PdfFormWidget form = pdf.Form as PdfFormWidget; for (int i = 0; i < form.FieldsWidget.Count; i++) { PdfSignatureFieldWidget field = form.FieldsWidget[i] as PdfSignatureFieldWidget; if (field != null && field.Signature != null) { PdfSignature signature = field.Signature; signatures.Add(signature); } } //Get the first signature PdfSignature signatureOne = signatures[0]; //Detect if the pdf document was modified bool modified = signatureOne.VerifyDocModified(); if (modified) { MessageBox.Show("The document was modified"); } else { MessageBox.Show("The document was not modified"); } } } catch (Exception exe) { MessageBox.Show(exe.Message, "Spire.Pdf Demo", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
/** * Signs a document with a PAdES-LTV Timestamp. The document is closed at the end. * @param sap the signature appearance * @param tsa the timestamp generator * @param signatureName the signature name or null to have a name generated * automatically * @throws Exception */ public static void Timestamp(PdfSignatureAppearance sap, ITSAClient tsa, String signatureName) { int contentEstimated = tsa.GetTokenSizeEstimate(); sap.AddDeveloperExtension(PdfDeveloperExtension.ESIC_1_7_EXTENSIONLEVEL5); sap.SetVisibleSignature(new Rectangle(0, 0, 0, 0), 1, signatureName); PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ETSI_RFC3161); dic.Put(PdfName.TYPE, PdfName.DOCTIMESTAMP); sap.CryptoDictionary = dic; Dictionary <PdfName, int> exc = new Dictionary <PdfName, int>(); exc[PdfName.CONTENTS] = contentEstimated * 2 + 2; sap.PreClose(exc); Stream data = sap.GetRangeStream(); IDigest messageDigest = tsa.GetMessageDigest(); byte[] buf = new byte[4096]; int n; while ((n = data.Read(buf, 0, buf.Length)) > 0) { messageDigest.BlockUpdate(buf, 0, n); } byte[] tsImprint = new byte[messageDigest.GetDigestSize()]; messageDigest.DoFinal(tsImprint, 0); byte[] tsToken; try { tsToken = tsa.GetTimeStampToken(tsImprint); } catch (Exception e) { throw new GeneralSecurityException(e.Message); } //TODO jbonilla Validar para el TSA de Certificado que devuelve un valor muy grande. if (contentEstimated + 2 < tsToken.Length) { throw new IOException("Not enough space"); } byte[] paddedSig = new byte[contentEstimated]; System.Array.Copy(tsToken, 0, paddedSig, 0, tsToken.Length); PdfDictionary dic2 = new PdfDictionary(); dic2.Put(PdfName.CONTENTS, new PdfString(paddedSig).SetHexWriting(true)); sap.Close(dic2); }
private void button1_Click(object sender, EventArgs e) { //Load PDF document from disk PdfDocument doc = new PdfDocument(); doc.LoadFromFile("../../../../../../Data/ExtractSignatureInfo.pdf"); List <PdfSignature> signatures = new List <PdfSignature>(); var form = (PdfFormWidget)doc.Form; for (int i = 0; i < form.FieldsWidget.Count; ++i) { var field = form.FieldsWidget[i] as PdfSignatureFieldWidget; if (field != null && field.Signature != null) { //Find signature and add in a list PdfSignature signature = field.Signature; signatures.Add(signature); } } //Get the first signature PdfSignature signatureOne = signatures[0]; X509Certificate2Collection collection = signatureOne.Certificates; foreach (var certificate in collection) { byte[] cerByte = certificate.Export(X509ContentType.Cert); using (FileStream fileStream = new FileStream("Export.cer", FileMode.Create)) { //Write the data to the file for (int i = 0; i < cerByte.Length; i++) { fileStream.WriteByte(cerByte[i]); } fileStream.Seek(0, SeekOrigin.Begin); //Read and verify the data for (int i = 0; i < fileStream.Length; i++) { if (cerByte[i] != fileStream.ReadByte()) { fileStream.Close(); } } } } MessageBox.Show("Succeed!"); }
private static void checkRevocation(PdfSignature signature, StringBuilder sb, PdfCertificateRevocationCheckMode mode) { PdfSignatureContents contents = signature.Contents; DateTime signingTime = signature.SigningTime ?? DateTime.MinValue; foreach (DateTime time in new DateTime[] { signingTime, DateTime.UtcNow }) { bool revoked = contents.CheckIfRevoked(mode, time); string status = revoked ? "Revoked" : "Valid"; string date = time.ToShortDateString(); sb.AppendFormat("Checking using {0} mode: {1} on {2}\n", mode, status, date); } sb.AppendLine(); }
private static string processByPdfPKCS7(PdfDocument document, PdfSignature signature, string subFilter) { string output = string.Empty; PdfPKCS7 pkcs7 = new PdfPKCS7(signature.GetContents().GetValueBytes(), new iText.Kernel.Pdf.PdfName(subFilter)); X509Certificate signingCert = pkcs7.GetSigningCertificate(); DateTime signingTime = pkcs7.GetSignDate(); string digestAlgOid; byte[] messageDigest; bool isEpes; getAdditionalInfos(signature.GetContents().GetValueBytes(), subFilter, out digestAlgOid, out messageDigest, out isEpes); if (messageDigest == null) { messageDigest = GetByteRangeDigest(document, pkcs7, signature, digestAlgOid); } TimeStampToken timeStampToken = pkcs7.GetTimeStampToken(); string signatureFormat = timeStampToken == null ? "PadesBPLevelB" : "PadesBPLevelT"; output += "<SignerInfo>"; output += "<DigestAlgOid>" + digestAlgOid + "</DigestAlgOid>"; output += "<MessageDigest>" + (messageDigest != null ? Convert.ToBase64String(messageDigest) : "") + "</MessageDigest>"; output += "<SignatureType>" + signatureFormat + "</SignatureType>"; output += "<SigningCertificate>" + Convert.ToBase64String(signingCert.GetEncoded()) + "</SigningCertificate>"; output += "<SigningTimeUtc>" + (signingTime != DateTime.MinValue ? signingTime.ToUniversalTime().ToString("o") : "") + "</SigningTimeUtc>"; output += "<TimeStamps>"; if (timeStampToken != null) { output += "<TimeStamp>"; output += "<TimeStampDateTimeUtc>"; output += DateTime.SpecifyKind(timeStampToken.TimeStampInfo.GenTime, DateTimeKind.Utc).ToUniversalTime().ToString("o"); output += "</TimeStampDateTimeUtc>"; output += "<TimeStampSigningCertificate>"; output += Convert.ToBase64String(getTimeStampCert(timeStampToken).GetEncoded()); output += "</TimeStampSigningCertificate>"; output += "</TimeStamp>"; } output += "</TimeStamps>"; output += "</SignerInfo>"; return(output); }
private void button1_Click(object sender, EventArgs e) { string inputFile = @"..\..\..\..\..\..\Data\DigitalSignature.pdf"; //load a PDF document PdfDocument doc = new PdfDocument(); doc.LoadFromFile(inputFile); //Load a certificate .pfx file String pfxPath = @"..\..\..\..\..\..\Data\gary.pfx"; PdfCertificate cert = new PdfCertificate(pfxPath, "e-iceblue", System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.Exportable); //Add a signature to the specified position PdfSignature signature = new PdfSignature(doc, doc.Pages[0], cert, "signature"); signature.Bounds = new RectangleF(new PointF(90, 550), new SizeF(180, 90)); //Set the signature content signature.NameLabel = "Digitally signed by:Gary"; signature.LocationInfoLabel = "Location:"; signature.LocationInfo = "CN"; signature.ReasonLabel = "Reason: "; signature.Reason = "Ensure authenticity"; signature.ContactInfoLabel = "Contact Number: "; signature.ContactInfo = "028-81705109"; signature.DocumentPermissions = PdfCertificationFlags.AllowFormFill | PdfCertificationFlags.ForbidChanges; signature.GraphicsMode = GraphicMode.SignImageAndSignDetail; signature.SignImageSource = PdfImage.FromFile(@"..\..\..\..\..\..\Data\logo.png"); //Configure a timestamp server string url = "https://freetsa.org/tsr"; signature.ConfigureTimestamp(url); //Save to file string output = "result.pdf"; doc.SaveToFile(output, FileFormat.PDF); //Launch the file PDFDocumentViewer(output); }
private static void SetSigCryptoFromX509(PdfSignatureAppearance sigAppearance, X509Certificate2 card, X509Certificate[] chain) { sigAppearance.SetCrypto(null, chain, null, PdfSignatureAppearance.WINCER_SIGNED); var dic = new PdfSignature(PdfName.ADOBE_PPKMS, PdfName.ADBE_PKCS7_SHA1) { Date = new PdfDate(sigAppearance.SignDate), Name = PdfPKCS7.GetSubjectFields(chain[0]).GetField("CN"), Reason = sigAppearance.Reason, Location = sigAppearance.Location }; sigAppearance.CryptoDictionary = dic; const int csize = 4000; var exc = new Dictionary <PdfName, int> { { PdfName.CONTENTS, csize * 2 + 2 } }; sigAppearance.PreClose(exc); HashAlgorithm sha = new SHA1CryptoServiceProvider(); var s = sigAppearance.RangeStream; int read; var buff = new byte[8192]; while ((read = s.Read(buff, 0, 8192)) > 0) { sha.TransformBlock(buff, 0, read, buff, 0); } sha.TransformFinalBlock(buff, 0, 0); var pk = SignMsg(sha.Hash, card, false); var outc = new byte[csize]; var dic2 = new PdfDictionary(); Array.Copy(pk, 0, outc, 0, pk.Length); dic2.Put(PdfName.CONTENTS, new PdfString(outc).SetHexWriting(true)); sigAppearance.Close(dic2); }
/** * Signs a document with a PAdES-LTV Timestamp. The document is closed at the end. * @param sap the signature appearance * @param tsa the timestamp generator * @param signatureName the signature name or null to have a name generated * automatically * @throws Exception */ public static void Timestamp(PdfSignatureAppearance sap, ITSAClient tsa, String signatureName) { int contentEstimated = tsa.GetTokenSizeEstimate(); sap.AddDeveloperExtension(PdfDeveloperExtension.ESIC_1_7_EXTENSIONLEVEL5); sap.SetVisibleSignature(new Rectangle(0,0,0,0), 1, signatureName); PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ETSI_RFC3161); dic.Put(PdfName.TYPE, PdfName.DOCTIMESTAMP); sap.CryptoDictionary = dic; Dictionary<PdfName,int> exc = new Dictionary<PdfName,int>(); exc[PdfName.CONTENTS] = contentEstimated * 2 + 2; sap.PreClose(exc); Stream data = sap.GetRangeStream(); IDigest messageDigest = tsa.GetMessageDigest(); byte[] buf = new byte[4096]; int n; while ((n = data.Read(buf, 0, buf.Length)) > 0) { messageDigest.BlockUpdate(buf, 0, n); } byte[] tsImprint = new byte[messageDigest.GetDigestSize()]; messageDigest.DoFinal(tsImprint, 0); byte[] tsToken; try { tsToken = tsa.GetTimeStampToken(tsImprint); } catch(Exception e) { throw new GeneralSecurityException(e.Message); } //TODO jbonilla Validar para el TSA de Certificado que devuelve un valor muy grande. if (contentEstimated + 2 < tsToken.Length) throw new IOException("Not enough space"); byte[] paddedSig = new byte[contentEstimated]; System.Array.Copy(tsToken, 0, paddedSig, 0, tsToken.Length); PdfDictionary dic2 = new PdfDictionary(); dic2.Put(PdfName.CONTENTS, new PdfString(paddedSig).SetHexWriting(true)); sap.Close(dic2); }
/** * Signs the document using the detached mode, CMS or CAdES equivalent. * @param sap the PdfSignatureAppearance * @param externalSignature the interface providing the actual signing * @param chain the certificate chain * @param crlList the CRL list * @param ocspClient the OCSP client * @param tsaClient the Timestamp client * @param provider the provider or null * @param estimatedSize the reserved size for the signature. It will be estimated if 0 * @param cades true to sign CAdES equivalent PAdES-BES, false to sign CMS * @throws DocumentException * @throws IOException * @throws GeneralSecurityException * @throws NoSuchAlgorithmException * @throws Exception */ public static void SignDetached(PdfSignatureAppearance sap, IExternalSignature externalSignature, ICollection<X509Certificate> chain, ICollection<ICrlClient> crlList, IOcspClient ocspClient, ITSAClient tsaClient, int estimatedSize, CryptoStandard sigtype) { List<X509Certificate> certa = new List<X509Certificate>(chain); ICollection<byte[]> crlBytes = null; int i = 0; while (crlBytes == null && i < certa.Count) crlBytes = ProcessCrl(certa[i++], crlList); if (estimatedSize == 0) { estimatedSize = 8192; if (crlBytes != null) { foreach (byte[] element in crlBytes) { estimatedSize += element.Length + 10; } } if (ocspClient != null) estimatedSize += 4192; if (tsaClient != null) estimatedSize += 4192; } sap.Certificate = certa[0]; if(sigtype == CryptoStandard.CADES) sap.AddDeveloperExtension(PdfDeveloperExtension.ESIC_1_7_EXTENSIONLEVEL2); PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, sigtype == CryptoStandard.CADES ? PdfName.ETSI_CADES_DETACHED : PdfName.ADBE_PKCS7_DETACHED); dic.Reason = sap.Reason; dic.Location = sap.Location; dic.SignatureCreator = sap.SignatureCreator; dic.Contact = sap.Contact; dic.Date = new PdfDate(sap.SignDate); // time-stamp will over-rule this sap.CryptoDictionary = dic; Dictionary<PdfName, int> exc = new Dictionary<PdfName, int>(); exc[PdfName.CONTENTS] = estimatedSize * 2 + 2; sap.PreClose(exc); String hashAlgorithm = externalSignature.GetHashAlgorithm(); PdfPKCS7 sgn = new PdfPKCS7(null, chain, hashAlgorithm, false); IDigest messageDigest = DigestUtilities.GetDigest(hashAlgorithm); Stream data = sap.GetRangeStream(); byte[] hash = DigestAlgorithms.Digest(data, hashAlgorithm); DateTime cal = DateTime.Now; byte[] ocsp = null; if (chain.Count >= 2 && ocspClient != null) { ocsp = ocspClient.GetEncoded(certa[0], certa[1], null); } byte[] sh = sgn.getAuthenticatedAttributeBytes(hash, cal, ocsp, crlBytes, sigtype); byte[] extSignature = externalSignature.Sign(sh); sgn.SetExternalDigest(extSignature, null, externalSignature.GetEncryptionAlgorithm()); byte[] encodedSig = sgn.GetEncodedPKCS7(hash, cal, tsaClient, ocsp, crlBytes, sigtype); if (estimatedSize < encodedSig.Length) throw new IOException("Not enough space"); byte[] paddedSig = new byte[estimatedSize]; System.Array.Copy(encodedSig, 0, paddedSig, 0, encodedSig.Length); PdfDictionary dic2 = new PdfDictionary(); dic2.Put(PdfName.CONTENTS, new PdfString(paddedSig).SetHexWriting(true)); sap.Close(dic2); }
/** * Sign the document using an external container, usually a PKCS7. The signature is fully composed * externally, iText will just put the container inside the document. * @param sap the PdfSignatureAppearance * @param externalSignatureContainer the interface providing the actual signing * @param estimatedSize the reserved size for the signature * @throws GeneralSecurityException * @throws IOException * @throws DocumentException */ public static void SignExternalContainer(PdfSignatureAppearance sap, IExternalSignatureContainer externalSignatureContainer, int estimatedSize) { PdfSignature dic = new PdfSignature(null, null); dic.Reason = sap.Reason; dic.Location = sap.Location; dic.SignatureCreator = sap.SignatureCreator; dic.Contact = sap.Contact; dic.Date = new PdfDate(sap.SignDate); // time-stamp will over-rule this externalSignatureContainer.ModifySigningDictionary(dic); sap.CryptoDictionary = dic; Dictionary<PdfName, int> exc = new Dictionary<PdfName, int>(); exc[PdfName.CONTENTS] = estimatedSize * 2 + 2; sap.PreClose(exc); Stream data = sap.GetRangeStream(); byte[] encodedSig = externalSignatureContainer.Sign(data); if (estimatedSize < encodedSig.Length) throw new IOException("Not enough space"); byte[] paddedSig = new byte[estimatedSize]; System.Array.Copy(encodedSig, 0, paddedSig, 0, encodedSig.Length); PdfDictionary dic2 = new PdfDictionary(); dic2.Put(PdfName.CONTENTS, new PdfString(paddedSig).SetHexWriting(true)); sap.Close(dic2); }