public void Sign(String src, String name, String dest, ICollection <X509Certificate> chain, ICipherParameters pk, String digestAlgorithm, CryptoStandard subfilter, String reason, String location, String contact, DateTime signDate, String fullName) { // Creating the reader and the stamper PdfReader reader = new PdfReader(src); FileStream os = new FileStream(dest, FileMode.Create); PdfStamper stamper = PdfStamper.CreateSignature(reader, os, '\0'); // Creating the appearance PdfSignatureAppearance appearance = stamper.SignatureAppearance; appearance.Reason = reason; appearance.Location = location; appearance.SetVisibleSignature(name); appearance.Contact = contact; appearance.SignDate = signDate; MySignatureEvent eEvent = new MySignatureEvent(); eEvent.FullName = fullName; appearance.SignatureEvent = eEvent; // Creating the signature IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm); MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, subfilter); }
/** * 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); }
public void Sign(String src, String dest, ICollection<X509Certificate> chain, X509Certificate2 pk, String digestAlgorithm, CryptoStandard subfilter, String reason, String location, ICollection<ICrlClient> crlList, IOcspClient ocspClient, ITSAClient tsaClient, int estimatedSize) { // Creating the reader and the stamper PdfReader reader = null; PdfStamper stamper = null; FileStream os = null; try { reader = new PdfReader(src); os = new FileStream(dest, FileMode.Create); stamper = PdfStamper.CreateSignature(reader, os, '\0'); // Creating the appearance PdfSignatureAppearance appearance = stamper.SignatureAppearance; appearance.Reason = reason; appearance.Location = location; appearance.SetVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig"); // Creating the signature IExternalSignature pks = new X509Certificate2Signature(pk, digestAlgorithm); MakeSignature.SignDetached(appearance, pks, chain, crlList, ocspClient, tsaClient, estimatedSize, subfilter); } finally { if (reader != null) reader.Close(); if (stamper != null) stamper.Close(); if (os != null) os.Close(); } }
public void Sign(String src, String dest, ICollection <X509Certificate> chain, ICipherParameters pk, String digestAlgorithm, CryptoStandard subfilter, String reason, String location) { // Creating the reader and the stamper PdfReader reader = new PdfReader(src); FileStream os = new FileStream(dest, FileMode.Create); PdfStamper stamper = PdfStamper.CreateSignature(reader, os, '\0'); // Creating the appearance PdfSignatureAppearance appearance = stamper.SignatureAppearance; appearance.Reason = reason; appearance.Location = location; appearance.SetVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig"); // Creating the signature IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm); MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, subfilter); }
public void Sign(String src, String dest, ICollection <X509Certificate> chain, X509Certificate2 pk, String digestAlgorithm, CryptoStandard subfilter, String reason, String location, ICollection <ICrlClient> crlList, IOcspClient ocspClient, ITSAClient tsaClient, int estimatedSize) { // Creating the reader and the stamper PdfReader reader = null; PdfStamper stamper = null; FileStream os = null; try { reader = new PdfReader(src); os = new FileStream(dest, FileMode.Create); stamper = PdfStamper.CreateSignature(reader, os, '\0'); // Creating the appearance PdfSignatureAppearance appearance = stamper.SignatureAppearance; appearance.Reason = reason; appearance.Location = location; appearance.SetVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig"); // Creating the signature IExternalSignature pks = new X509Certificate2Signature(pk, digestAlgorithm); MakeSignature.SignDetached(appearance, pks, chain, crlList, ocspClient, tsaClient, estimatedSize, subfilter); } finally { if (reader != null) { reader.Close(); } if (stamper != null) { stamper.Close(); } if (os != null) { os.Close(); } } }
private static byte[] AddPdfSignatureField(byte[] src, ICollection <Org.BouncyCastle.X509.X509Certificate> chain, X509Certificate2 pk, string digestAlgorithm, CryptoStandard subfilter, string reason, string location, ICollection <ICrlClient> crlList, IOcspClient ocspClient, ITSAClient tsaClient, int estimatedSize, int page, Rectangle rectangle, string signatureFieldName) { // Creating the reader and the stamper PdfReader reader = null; PdfStamper stamper = null; var os = new MemoryStream(); try { reader = new PdfReader(src); stamper = PdfStamper.CreateSignature(reader, os, '\0'); // Creating the appearance var appearance = stamper.SignatureAppearance; appearance.Reason = reason; appearance.Location = location; appearance.SetVisibleSignature(rectangle, page, signatureFieldName); // Creating the signature IExternalSignature pks = new X509Certificate2Signature(pk, digestAlgorithm); MakeSignature.SignDetached(appearance, pks, chain, crlList, ocspClient, tsaClient, estimatedSize, subfilter); return(os.ToArray()); } finally { if (reader != null) { reader.Close(); } if (stamper != null) { stamper.Close(); } } }
public void Sign1(String src, String name, String dest, ICollection <X509Certificate> chain, ICipherParameters pk, String digestAlgorithm, CryptoStandard subfilter, String reason, String location) { // Creating the reader and the stamper PdfReader reader = new PdfReader(src); FileStream os = new FileStream(dest, FileMode.Create); PdfStamper stamper = PdfStamper.CreateSignature(reader, os, '\0'); // Creating the appearance PdfSignatureAppearance appearance = stamper.SignatureAppearance; appearance.Reason = reason; appearance.Location = location; appearance.SetVisibleSignature(name); // Custom text and custom font appearance.Layer2Text = "This document was signed by Bruno Specimen"; appearance.Layer2Font = new Font(Font.FontFamily.TIMES_ROMAN); // Creating the signature IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm); MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, subfilter); }
public void Sign4(String src, String name, String dest, ICollection <X509Certificate> chain, ICipherParameters pk, String digestAlgorithm, CryptoStandard subfilter, String reason, String location) { // Creating the reader and the stamper PdfReader reader = new PdfReader(src); FileStream os = new FileStream(dest, FileMode.Create); PdfStamper stamper = PdfStamper.CreateSignature(reader, os, '\0'); // Creating the appearance PdfSignatureAppearance appearance = stamper.SignatureAppearance; appearance.Reason = reason; appearance.Location = location; appearance.SetVisibleSignature(name); // Default text and scaled background image appearance.Image = Image.GetInstance(IMG); appearance.ImageScale = -1; // Creating the signature IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm); MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, subfilter); }
public void Sign(String src, String name, String dest, ICollection <X509Certificate> chain, ICipherParameters pk, String digestAlgorithm, CryptoStandard subfilter, String reason, String location, PdfSignatureAppearance.RenderingMode renderingMode, Image image) { // Creating the reader and the stamper PdfReader reader = new PdfReader(src); FileStream os = new FileStream(dest, FileMode.Create); PdfStamper stamper = PdfStamper.CreateSignature(reader, os, '\0'); // Creating the appearance PdfSignatureAppearance appearance = stamper.SignatureAppearance; appearance.Reason = reason; appearance.Location = location; appearance.SetVisibleSignature(name); appearance.Layer2Text = "Signed on " + DateTime.Now; appearance.SignatureRenderingMode = renderingMode; appearance.SignatureGraphic = image; // Creating the signature IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm); MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, subfilter); }
public void Sign2(String src, String name, String dest, ICollection <X509Certificate> chain, ICipherParameters pk, String digestAlgorithm, CryptoStandard subfilter, String reason, String location) { // Creating the reader and the stamper PdfReader reader = new PdfReader(src); FileStream os = new FileStream(dest, FileMode.Create); PdfStamper stamper = PdfStamper.CreateSignature(reader, os, '\0'); // Creating the appearance PdfSignatureAppearance appearance = stamper.SignatureAppearance; appearance.Reason = reason; appearance.Location = location; appearance.SetVisibleSignature(name); // Custom text, custom font, and right-to-left writing appearance.Layer2Text = "\u0644\u0648\u0631\u0627\u0646\u0633 \u0627\u0644\u0639\u0631\u0628"; appearance.RunDirection = PdfWriter.RUN_DIRECTION_RTL; appearance.Layer2Font = new Font(BaseFont.CreateFont("C:/windows/fonts/arialuni.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED), 12); // Creating the signature IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm); MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, subfilter); }
/// <summary> /// /// </summary> /// <param name="input"></param> /// <param name="chain"></param> /// <param name="pks"></param> /// <param name="subfilter"></param> /// <param name="reason"></param> /// <param name="location"></param> /// <param name="crlList"></param> /// <param name="ocspClient"></param> /// <param name="tsaClient"></param> /// <param name="estimatedSize"></param> /// <returns></returns> private static byte[] SignDocument(String input, ICollection<Org.BouncyCastle.X509.X509Certificate> chain, IExternalSignature pks, CryptoStandard subfilter, String reason, String location, ICollection<ICrlClient> crlList, IOcspClient ocspClient, ITSAClient tsaClient, int estimatedSize) { using (var stream = new MemoryStream()) { // Creating the reader and the stamper PdfReader reader = null; PdfStamper stamper = null; try { reader = new PdfReader(input); stamper = PdfStamper.CreateSignature(reader, stream, '\0'); // Creating the appearance PdfSignatureAppearance appearance = stamper.SignatureAppearance; appearance.Reason = reason; appearance.Location = location; //appearance.SetVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig"); // Creating the signature MakeSignature.SignDetached(appearance, pks, chain, crlList, ocspClient, tsaClient, estimatedSize, subfilter); } finally { reader?.Close(); stamper?.Close(); } return stream.GetBuffer(); } }
public void Sign(String src, String name, String dest, ICollection <X509Certificate> chain, ICipherParameters pk, String digestAlgorithm, CryptoStandard subfilter, String reason, String location) { // Creating the reader and the stamper PdfReader reader = new PdfReader(src); FileStream os = new FileStream(dest, FileMode.Create); PdfStamper stamper = PdfStamper.CreateSignature(reader, os, '\0'); // Creating the appearance PdfSignatureAppearance appearance = stamper.SignatureAppearance; appearance.Reason = reason; appearance.Location = location; appearance.SetVisibleSignature(name); // Creating the appearance for layer 0 PdfTemplate n0 = appearance.GetLayer(0); float x = n0.BoundingBox.Left; float y = n0.BoundingBox.Bottom; float width = n0.BoundingBox.Width; float height = n0.BoundingBox.Height; n0.SetColorFill(BaseColor.LIGHT_GRAY); n0.Rectangle(x, y, width, height); n0.Fill(); // Creating the appearance for layer 2 PdfTemplate n2 = appearance.GetLayer(2); ColumnText ct = new ColumnText(n2); ct.SetSimpleColumn(n2.BoundingBox); Paragraph p = new Paragraph("This document was signed by Bruno Specimen."); ct.AddElement(p); ct.Go(); // Creating the signature IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm); MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, subfilter); }
public void Sign(String src, String dest, ICollection <X509Certificate> chain, X509Certificate2 pk, String digestAlgorithm, CryptoStandard subfilter, String reason, String location, ICollection <ICrlClient> crlList, IOcspClient ocspClient, ITSAClient tsaClient, int estimatedSize, int RowIdx, int RowHeight, int x, int y, int NameWidth, int DateWidth, String RevIndex, String RevStep, String Reason, String Name, String Date) { // Creating the reader and the stamper PdfReader reader = null; PdfStamper stamper = null; FileStream os = null; try { reader = new PdfReader(src); os = new FileStream(dest, FileMode.Create); // os = new FileStream(dest, FileMode.Create, FileAccess.Write); //Activate MultiSignatures stamper = PdfStamper.CreateSignature(reader, os, '\0', null, true); //To disable Multi signatures uncomment this line : every new signature will invalidate older ones ! //stamper = PdfStamper.CreateSignature(reader, os, '\0'); // Creating the appearance PdfSignatureAppearance appearance = stamper.SignatureAppearance; Rectangle rectangle = new Rectangle(x, y + RowIdx * RowHeight, x + NameWidth + DateWidth, y + (RowIdx + 1) * RowHeight); appearance.SetVisibleSignature(rectangle, 1, "Revision " + RevIndex + "|" + RevStep); appearance.Reason = "marked as changed"; appearance.Location = location; appearance.Layer2Text = "Signed on " + DateTime.Now; appearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.DESCRIPTION; PdfTemplate n2 = appearance.GetLayer(2); Font font = new Font(); font.SetColor(255, 0, 0); font.Size = 10; ColumnText ct1 = new ColumnText(n2); ct1.SetSimpleColumn(new Phrase(Name, font), 0, 0, NameWidth, rectangle.Height, 15, Element.ALIGN_LEFT); ct1.Go(); ColumnText ct2 = new ColumnText(n2); ct2.SetSimpleColumn(new Phrase(Date, font), NameWidth, 0, rectangle.Width, rectangle.Height, 15, Element.ALIGN_LEFT); ct2.Go(); //n2.ConcatCTM(1, 0, 0, -1, 0, 0); //n2.SaveState(); // Creating the signature IExternalSignature pks = new X509Certificate2Signature(pk, digestAlgorithm); MakeSignature.SignDetached(appearance, pks, chain, crlList, ocspClient, tsaClient, estimatedSize, subfilter); } catch (Exception ex) { Console.WriteLine("GMA: " + ex.Message); } finally { if (reader != null) { reader.Close(); } if (stamper != null) { stamper.Close(); } if (os != null) { os.Close(); } } }
public virtual byte[] getAuthenticatedAttributeBytes(byte[] secondDigest, byte[] ocsp, ICollection <byte[]> crlBytes, CryptoStandard sigtype);
/// Gets the bytes for the PKCS7SignedData object. Optionally the authenticatedAttributes /// in the signerInfo can also be set, OR a time-stamp-authority client /// may be provided. /// @param secondDigest the digest in the authenticatedAttributes /// @param tsaClient TSAClient - null or an optional time stamp authority client /// @return byte[] the bytes for the PKCS7SignedData object /// @since 2.1.6 public virtual byte[] GetEncodedPKCS7(byte[] secondDigest, ITSAClient tsaClient, byte[] ocsp, ICollection <byte[]> crlBytes, CryptoStandard sigtype);
// Authenticated attributes /** * When using authenticatedAttributes the authentication process is different. * The document digest is generated and put inside the attribute. The signing is done over the DER encoded * authenticatedAttributes. This method provides that encoding and the parameters must be * exactly the same as in {@link #getEncodedPKCS7(byte[],Calendar)}. * <p> * A simple example: * <p> * <pre> * Calendar cal = Calendar.getInstance(); * PdfPKCS7 pk7 = new PdfPKCS7(key, chain, null, "SHA1", null, false); * MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); * byte buf[] = new byte[8192]; * int n; * InputStream inp = sap.getRangeStream(); * while ((n = inp.read(buf)) > 0) { * messageDigest.update(buf, 0, n); * } * byte hash[] = messageDigest.digest(); * byte sh[] = pk7.getAuthenticatedAttributeBytes(hash, cal); * pk7.update(sh, 0, sh.length); * byte sg[] = pk7.getEncodedPKCS7(hash, cal); * </pre> * @param secondDigest the content digest * @param signingTime the signing time * @return the byte array representation of the authenticatedAttributes ready to be signed */ public byte[] getAuthenticatedAttributeBytes(byte[] secondDigest, DateTime signingTime, byte[] ocsp, ICollection<byte[]> crlBytes, CryptoStandard sigtype) { return GetAuthenticatedAttributeSet(secondDigest, signingTime, ocsp, crlBytes, sigtype).GetEncoded(Asn1Encodable.Der); }
/** * Gets the bytes for the PKCS7SignedData object. Optionally the authenticatedAttributes * in the signerInfo can also be set, OR a time-stamp-authority client * may be provided. * @param secondDigest the digest in the authenticatedAttributes * @param signingTime the signing time in the authenticatedAttributes * @param tsaClient TSAClient - null or an optional time stamp authority client * @return byte[] the bytes for the PKCS7SignedData object * @since 2.1.6 */ public byte[] GetEncodedPKCS7(byte[] secondDigest, DateTime signingTime, ITSAClient tsaClient, byte[] ocsp, ICollection<byte[]> crlBytes, CryptoStandard sigtype) { if (externalDigest != null) { digest = externalDigest; if (RSAdata != null) RSAdata = externalRSAdata; } else if (externalRSAdata != null && RSAdata != null) { RSAdata = externalRSAdata; sig.BlockUpdate(RSAdata, 0, RSAdata.Length); digest = sig.GenerateSignature(); } else { if (RSAdata != null) { RSAdata = new byte[messageDigest.GetDigestSize()]; messageDigest.DoFinal(RSAdata, 0); sig.BlockUpdate(RSAdata, 0, RSAdata.Length); } digest = sig.GenerateSignature(); } // Create the set of Hash algorithms Asn1EncodableVector digestAlgorithms = new Asn1EncodableVector(); foreach (string dal in digestalgos.Keys) { Asn1EncodableVector algos = new Asn1EncodableVector(); algos.Add(new DerObjectIdentifier(dal)); algos.Add(DerNull.Instance); digestAlgorithms.Add(new DerSequence(algos)); } // Create the contentInfo. Asn1EncodableVector v = new Asn1EncodableVector(); v.Add(new DerObjectIdentifier(SecurityIDs.ID_PKCS7_DATA)); if (RSAdata != null) v.Add(new DerTaggedObject(0, new DerOctetString(RSAdata))); DerSequence contentinfo = new DerSequence(v); // Get all the certificates // v = new Asn1EncodableVector(); foreach (X509Certificate xcert in certs) { Asn1InputStream tempstream = new Asn1InputStream(new MemoryStream(xcert.GetEncoded())); v.Add(tempstream.ReadObject()); } DerSet dercertificates = new DerSet(v); // Create signerinfo structure. // Asn1EncodableVector signerinfo = new Asn1EncodableVector(); // Add the signerInfo version // signerinfo.Add(new DerInteger(signerversion)); v = new Asn1EncodableVector(); v.Add(CertificateInfo.GetIssuer(signCert.GetTbsCertificate())); v.Add(new DerInteger(signCert.SerialNumber)); signerinfo.Add(new DerSequence(v)); // Add the digestAlgorithm v = new Asn1EncodableVector(); v.Add(new DerObjectIdentifier(digestAlgorithmOid)); v.Add(DerNull.Instance); signerinfo.Add(new DerSequence(v)); // add the authenticated attribute if present if (secondDigest != null /*&& signingTime != null*/) { signerinfo.Add(new DerTaggedObject(false, 0, GetAuthenticatedAttributeSet(secondDigest, signingTime, ocsp, crlBytes, sigtype))); } // Add the digestEncryptionAlgorithm v = new Asn1EncodableVector(); v.Add(new DerObjectIdentifier(digestEncryptionAlgorithmOid)); v.Add(DerNull.Instance); signerinfo.Add(new DerSequence(v)); // Add the digest signerinfo.Add(new DerOctetString(digest)); // When requested, go get and add the timestamp. May throw an exception. // Added by Martin Brunecky, 07/12/2007 folowing Aiken Sam, 2006-11-15 // Sam found Adobe expects time-stamped SHA1-1 of the encrypted digest if (tsaClient != null) { byte[] tsImprint = DigestAlgorithms.Digest(tsaClient.GetMessageDigest(), digest); byte[] tsToken = tsaClient.GetTimeStampToken(tsImprint); if (tsToken != null) { Asn1EncodableVector unauthAttributes = BuildUnauthenticatedAttributes(tsToken); if (unauthAttributes != null) { signerinfo.Add(new DerTaggedObject(false, 1, new DerSet(unauthAttributes))); } } } // Finally build the body out of all the components above Asn1EncodableVector body = new Asn1EncodableVector(); body.Add(new DerInteger(version)); body.Add(new DerSet(digestAlgorithms)); body.Add(contentinfo); body.Add(new DerTaggedObject(false, 0, dercertificates)); // Only allow one signerInfo body.Add(new DerSet(new DerSequence(signerinfo))); // Now we have the body, wrap it in it's PKCS7Signed shell // and return it // Asn1EncodableVector whole = new Asn1EncodableVector(); whole.Add(new DerObjectIdentifier(SecurityIDs.ID_PKCS7_SIGNED_DATA)); whole.Add(new DerTaggedObject(0, new DerSequence(body))); MemoryStream bOut = new MemoryStream(); Asn1OutputStream dout = new Asn1OutputStream(bOut); dout.WriteObject(new DerSequence(whole)); dout.Close(); return bOut.ToArray(); }
/** * Gets the bytes for the PKCS7SignedData object. Optionally the authenticatedAttributes * in the signerInfo can also be set, OR a time-stamp-authority client * may be provided. * @param secondDigest the digest in the authenticatedAttributes * @param signingTime the signing time in the authenticatedAttributes * @param tsaClient TSAClient - null or an optional time stamp authority client * @return byte[] the bytes for the PKCS7SignedData object * @since 2.1.6 */ public byte[] GetEncodedPKCS7(byte[] secondDigest, DateTime signingTime, ITSAClient tsaClient, byte[] ocsp, ICollection <byte[]> crlBytes, CryptoStandard sigtype) { if (externalDigest != null) { digest = externalDigest; if (RSAdata != null) { RSAdata = externalRSAdata; } } else if (externalRSAdata != null && RSAdata != null) { RSAdata = externalRSAdata; sig.BlockUpdate(RSAdata, 0, RSAdata.Length); digest = sig.GenerateSignature(); } else { if (RSAdata != null) { RSAdata = new byte[messageDigest.GetDigestSize()]; messageDigest.DoFinal(RSAdata, 0); sig.BlockUpdate(RSAdata, 0, RSAdata.Length); } digest = sig.GenerateSignature(); } // Create the set of Hash algorithms Asn1EncodableVector digestAlgorithms = new Asn1EncodableVector(); foreach (string dal in digestalgos.Keys) { Asn1EncodableVector algos = new Asn1EncodableVector(); algos.Add(new DerObjectIdentifier(dal)); algos.Add(DerNull.Instance); digestAlgorithms.Add(new DerSequence(algos)); } // Create the contentInfo. Asn1EncodableVector v = new Asn1EncodableVector(); v.Add(new DerObjectIdentifier(SecurityIDs.ID_PKCS7_DATA)); if (RSAdata != null) { v.Add(new DerTaggedObject(0, new DerOctetString(RSAdata))); } DerSequence contentinfo = new DerSequence(v); // Get all the certificates // v = new Asn1EncodableVector(); foreach (X509Certificate xcert in certs) { Asn1InputStream tempstream = new Asn1InputStream(new MemoryStream(xcert.GetEncoded())); v.Add(tempstream.ReadObject()); } DerSet dercertificates = new DerSet(v); // Create signerinfo structure. // Asn1EncodableVector signerinfo = new Asn1EncodableVector(); // Add the signerInfo version // signerinfo.Add(new DerInteger(signerversion)); v = new Asn1EncodableVector(); v.Add(CertificateInfo.GetIssuer(signCert.GetTbsCertificate())); v.Add(new DerInteger(signCert.SerialNumber)); signerinfo.Add(new DerSequence(v)); // Add the digestAlgorithm v = new Asn1EncodableVector(); v.Add(new DerObjectIdentifier(digestAlgorithmOid)); v.Add(DerNull.Instance); signerinfo.Add(new DerSequence(v)); // add the authenticated attribute if present if (secondDigest != null /*&& signingTime != null*/) { signerinfo.Add(new DerTaggedObject(false, 0, GetAuthenticatedAttributeSet(secondDigest, signingTime, ocsp, crlBytes, sigtype))); } // Add the digestEncryptionAlgorithm v = new Asn1EncodableVector(); v.Add(new DerObjectIdentifier(digestEncryptionAlgorithmOid)); v.Add(DerNull.Instance); signerinfo.Add(new DerSequence(v)); // Add the digest signerinfo.Add(new DerOctetString(digest)); // When requested, go get and add the timestamp. May throw an exception. // Added by Martin Brunecky, 07/12/2007 folowing Aiken Sam, 2006-11-15 // Sam found Adobe expects time-stamped SHA1-1 of the encrypted digest if (tsaClient != null) { byte[] tsImprint = DigestAlgorithms.Digest(tsaClient.GetMessageDigest(), digest); byte[] tsToken = tsaClient.GetTimeStampToken(tsImprint); if (tsToken != null) { Asn1EncodableVector unauthAttributes = BuildUnauthenticatedAttributes(tsToken); if (unauthAttributes != null) { signerinfo.Add(new DerTaggedObject(false, 1, new DerSet(unauthAttributes))); } } } // Finally build the body out of all the components above Asn1EncodableVector body = new Asn1EncodableVector(); body.Add(new DerInteger(version)); body.Add(new DerSet(digestAlgorithms)); body.Add(contentinfo); body.Add(new DerTaggedObject(false, 0, dercertificates)); // Only allow one signerInfo body.Add(new DerSet(new DerSequence(signerinfo))); // Now we have the body, wrap it in it's PKCS7Signed shell // and return it // Asn1EncodableVector whole = new Asn1EncodableVector(); whole.Add(new DerObjectIdentifier(SecurityIDs.ID_PKCS7_SIGNED_DATA)); whole.Add(new DerTaggedObject(0, new DerSequence(body))); MemoryStream bOut = new MemoryStream(); Asn1OutputStream dout = new Asn1OutputStream(bOut); dout.WriteObject(new DerSequence(whole)); dout.Close(); return(bOut.ToArray()); }
/** * This method provides that encoding and the parameters must be * exactly the same as in {@link #getEncodedPKCS7(byte[],Calendar)}. * * @param secondDigest the content digest * @param signingTime the signing time * @return the byte array representation of the authenticatedAttributes ready to be signed */ private DerSet GetAuthenticatedAttributeSet(byte[] secondDigest, DateTime signingTime, byte[] ocsp, ICollection<byte[]> crlBytes, CryptoStandard sigtype) { Asn1EncodableVector attribute = new Asn1EncodableVector(); Asn1EncodableVector v = new Asn1EncodableVector(); v.Add(new DerObjectIdentifier(SecurityIDs.ID_CONTENT_TYPE)); v.Add(new DerSet(new DerObjectIdentifier(SecurityIDs.ID_PKCS7_DATA))); attribute.Add(new DerSequence(v)); v = new Asn1EncodableVector(); v.Add(new DerObjectIdentifier(SecurityIDs.ID_SIGNING_TIME)); v.Add(new DerSet(new DerUtcTime(signingTime))); attribute.Add(new DerSequence(v)); v = new Asn1EncodableVector(); v.Add(new DerObjectIdentifier(SecurityIDs.ID_MESSAGE_DIGEST)); v.Add(new DerSet(new DerOctetString(secondDigest))); attribute.Add(new DerSequence(v)); bool haveCrl = false; if (crlBytes != null) { foreach (byte[] bCrl in crlBytes) { if (bCrl != null) { haveCrl = true; break; } } } if (ocsp != null || haveCrl) { v = new Asn1EncodableVector(); v.Add(new DerObjectIdentifier(SecurityIDs.ID_ADBE_REVOCATION)); Asn1EncodableVector revocationV = new Asn1EncodableVector(); if (haveCrl) { Asn1EncodableVector v2 = new Asn1EncodableVector(); foreach (byte[] bCrl in crlBytes) { if (bCrl == null) continue; Asn1InputStream t = new Asn1InputStream(bCrl); v2.Add(t.ReadObject()); } revocationV.Add(new DerTaggedObject(true, 0, new DerSequence(v2))); } if (ocsp != null) { DerOctetString doctet = new DerOctetString(ocsp); Asn1EncodableVector vo1 = new Asn1EncodableVector(); Asn1EncodableVector v2 = new Asn1EncodableVector(); v2.Add(OcspObjectIdentifiers.PkixOcspBasic); v2.Add(doctet); DerEnumerated den = new DerEnumerated(0); Asn1EncodableVector v3 = new Asn1EncodableVector(); v3.Add(den); v3.Add(new DerTaggedObject(true, 0, new DerSequence(v2))); vo1.Add(new DerSequence(v3)); revocationV.Add(new DerTaggedObject(true, 1, new DerSequence(vo1))); } v.Add(new DerSet(new DerSequence(revocationV))); attribute.Add(new DerSequence(v)); } if (sigtype == CryptoStandard.CADES) { v = new Asn1EncodableVector(); v.Add(new DerObjectIdentifier(SecurityIDs.ID_AA_SIGNING_CERTIFICATE_V2)); Asn1EncodableVector aaV2 = new Asn1EncodableVector(); AlgorithmIdentifier algoId = new AlgorithmIdentifier(new DerObjectIdentifier(digestAlgorithmOid), null); aaV2.Add(algoId); byte[] dig = DigestAlgorithms.Digest(GetHashAlgorithm(), signCert.GetEncoded()); aaV2.Add(new DerOctetString(dig)); v.Add(new DerSet(new DerSequence(new DerSequence(new DerSequence(aaV2))))); attribute.Add(new DerSequence(v)); } return new DerSet(attribute); }
public PDF_Signer() { //Default Crypto standard this.sigType = CryptoStandard.CADES; }
public PDF_Signer(CryptoStandard sigType) { this.sigType = sigType; }
/** * 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]; 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.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 + 2 < 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); }
/** * This method provides that encoding and the parameters must be * exactly the same as in {@link #getEncodedPKCS7(byte[],Calendar)}. * * @param secondDigest the content digest * @return the byte array representation of the authenticatedAttributes ready to be signed */ private DerSet GetAuthenticatedAttributeSet(byte[] secondDigest, byte[] ocsp, ICollection<byte[]> crlBytes, CryptoStandard sigtype) { Asn1EncodableVector attribute = new Asn1EncodableVector(); Asn1EncodableVector v = new Asn1EncodableVector(); v.Add(new DerObjectIdentifier(SecurityIDs.ID_CONTENT_TYPE)); v.Add(new DerSet(new DerObjectIdentifier(SecurityIDs.ID_PKCS7_DATA))); attribute.Add(new DerSequence(v)); v = new Asn1EncodableVector(); v.Add(new DerObjectIdentifier(SecurityIDs.ID_MESSAGE_DIGEST)); v.Add(new DerSet(new DerOctetString(secondDigest))); attribute.Add(new DerSequence(v)); bool haveCrl = false; if (crlBytes != null) { foreach (byte[] bCrl in crlBytes) { if (bCrl != null) { haveCrl = true; break; } } } if (ocsp != null || haveCrl) { v = new Asn1EncodableVector(); v.Add(new DerObjectIdentifier(SecurityIDs.ID_ADBE_REVOCATION)); Asn1EncodableVector revocationV = new Asn1EncodableVector(); if (haveCrl) { Asn1EncodableVector v2 = new Asn1EncodableVector(); foreach (byte[] bCrl in crlBytes) { if (bCrl == null) continue; Asn1InputStream t = new Asn1InputStream(bCrl); v2.Add(t.ReadObject()); } revocationV.Add(new DerTaggedObject(true, 0, new DerSequence(v2))); } if (ocsp != null) { DerOctetString doctet = new DerOctetString(ocsp); Asn1EncodableVector vo1 = new Asn1EncodableVector(); Asn1EncodableVector v2 = new Asn1EncodableVector(); v2.Add(OcspObjectIdentifiers.PkixOcspBasic); v2.Add(doctet); DerEnumerated den = new DerEnumerated(0); Asn1EncodableVector v3 = new Asn1EncodableVector(); v3.Add(den); v3.Add(new DerTaggedObject(true, 0, new DerSequence(v2))); vo1.Add(new DerSequence(v3)); revocationV.Add(new DerTaggedObject(true, 1, new DerSequence(vo1))); } v.Add(new DerSet(new DerSequence(revocationV))); attribute.Add(new DerSequence(v)); } if (sigtype == CryptoStandard.CADES) { v = new Asn1EncodableVector(); v.Add(new DerObjectIdentifier(SecurityIDs.ID_AA_SIGNING_CERTIFICATE_V2)); Asn1EncodableVector aaV2 = new Asn1EncodableVector(); String sha256Oid = DigestAlgorithms.GetAllowedDigests(DigestAlgorithms.SHA256); // If we look into X.690-0207, clause 11.5, we can see that using DER all the components of a sequence having // default values shall not be included. According to RFC 5035, 5.4.1.1, definition of ESSCertIDv2, default // AlgorithmIdentifier is sha256. if (!sha256Oid.Equals(digestAlgorithmOid)) { AlgorithmIdentifier algoId = new AlgorithmIdentifier(new DerObjectIdentifier(digestAlgorithmOid)); aaV2.Add(algoId); } byte[] dig = DigestAlgorithms.Digest(GetHashAlgorithm(), signCert.GetEncoded()); aaV2.Add(new DerOctetString(dig)); v.Add(new DerSet(new DerSequence(new DerSequence(new DerSequence(aaV2))))); attribute.Add(new DerSequence(v)); } return new DerSet(attribute); }
// Authenticated attributes /** * When using authenticatedAttributes the authentication process is different. * The document digest is generated and put inside the attribute. The signing is done over the DER encoded * authenticatedAttributes. This method provides that encoding and the parameters must be * exactly the same as in {@link #getEncodedPKCS7(byte[],Calendar)}. * <p> * A simple example: * <p> * <pre> * Calendar cal = Calendar.getInstance(); * PdfPKCS7 pk7 = new PdfPKCS7(key, chain, null, "SHA1", null, false); * MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); * byte buf[] = new byte[8192]; * int n; * InputStream inp = sap.getRangeStream(); * while ((n = inp.read(buf)) > 0) { * messageDigest.update(buf, 0, n); * } * byte hash[] = messageDigest.digest(); * byte sh[] = pk7.getAuthenticatedAttributeBytes(hash, cal); * pk7.update(sh, 0, sh.length); * byte sg[] = pk7.getEncodedPKCS7(hash, cal); * </pre> * @param secondDigest the content digest * @param signingTime the signing time * @return the byte array representation of the authenticatedAttributes ready to be signed */ public byte[] getAuthenticatedAttributeBytes(byte[] secondDigest, DateTime signingTime, byte[] ocsp, ICollection <byte[]> crlBytes, CryptoStandard sigtype) { return(GetAuthenticatedAttributeSet(secondDigest, signingTime, ocsp, crlBytes, sigtype).GetEncoded(Asn1Encodable.Der)); }
/** * 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) { SignDetached(sap, externalSignature, chain, crlList, ocspClient, tsaClient, estimatedSize, sigtype, (SignaturePolicyIdentifier)null); }
/** * This method provides that encoding and the parameters must be * exactly the same as in {@link #getEncodedPKCS7(byte[],Calendar)}. * * @param secondDigest the content digest * @param signingTime the signing time * @return the byte array representation of the authenticatedAttributes ready to be signed */ private DerSet GetAuthenticatedAttributeSet(byte[] secondDigest, DateTime signingTime, byte[] ocsp, ICollection <byte[]> crlBytes, CryptoStandard sigtype) { Asn1EncodableVector attribute = new Asn1EncodableVector(); Asn1EncodableVector v = new Asn1EncodableVector(); v.Add(new DerObjectIdentifier(SecurityIDs.ID_CONTENT_TYPE)); v.Add(new DerSet(new DerObjectIdentifier(SecurityIDs.ID_PKCS7_DATA))); attribute.Add(new DerSequence(v)); v = new Asn1EncodableVector(); v.Add(new DerObjectIdentifier(SecurityIDs.ID_SIGNING_TIME)); v.Add(new DerSet(new DerUtcTime(signingTime))); attribute.Add(new DerSequence(v)); v = new Asn1EncodableVector(); v.Add(new DerObjectIdentifier(SecurityIDs.ID_MESSAGE_DIGEST)); v.Add(new DerSet(new DerOctetString(secondDigest))); attribute.Add(new DerSequence(v)); bool haveCrl = false; if (crlBytes != null) { foreach (byte[] bCrl in crlBytes) { if (bCrl != null) { haveCrl = true; break; } } } if (ocsp != null || haveCrl) { v = new Asn1EncodableVector(); v.Add(new DerObjectIdentifier(SecurityIDs.ID_ADBE_REVOCATION)); Asn1EncodableVector revocationV = new Asn1EncodableVector(); if (haveCrl) { Asn1EncodableVector v2 = new Asn1EncodableVector(); foreach (byte[] bCrl in crlBytes) { if (bCrl == null) { continue; } Asn1InputStream t = new Asn1InputStream(bCrl); v2.Add(t.ReadObject()); } revocationV.Add(new DerTaggedObject(true, 0, new DerSequence(v2))); } if (ocsp != null) { DerOctetString doctet = new DerOctetString(ocsp); Asn1EncodableVector vo1 = new Asn1EncodableVector(); Asn1EncodableVector v2 = new Asn1EncodableVector(); v2.Add(OcspObjectIdentifiers.PkixOcspBasic); v2.Add(doctet); DerEnumerated den = new DerEnumerated(0); Asn1EncodableVector v3 = new Asn1EncodableVector(); v3.Add(den); v3.Add(new DerTaggedObject(true, 0, new DerSequence(v2))); vo1.Add(new DerSequence(v3)); revocationV.Add(new DerTaggedObject(true, 1, new DerSequence(vo1))); } v.Add(new DerSet(new DerSequence(revocationV))); attribute.Add(new DerSequence(v)); } if (sigtype == CryptoStandard.CADES) { v = new Asn1EncodableVector(); v.Add(new DerObjectIdentifier(SecurityIDs.ID_AA_SIGNING_CERTIFICATE_V2)); Asn1EncodableVector aaV2 = new Asn1EncodableVector(); AlgorithmIdentifier algoId = new AlgorithmIdentifier(new DerObjectIdentifier(digestAlgorithmOid), null); aaV2.Add(algoId); byte[] dig = DigestAlgorithms.Digest(GetHashAlgorithm(), signCert.GetEncoded()); aaV2.Add(new DerOctetString(dig)); v.Add(new DerSet(new DerSequence(new DerSequence(new DerSequence(aaV2))))); attribute.Add(new DerSequence(v)); } return(new DerSet(attribute)); }