/** * 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); }
private static void Sign(XmlElement signature, IXmlLocator xmlLocator, IExternalSignature externalSignature, List <XmlElement> references, XmlElement dsObject, KeyInfoClause keyInfo) { XmlDocument originalDoc = xmlLocator.GetDocument(); if (signature == null) { throw new InvalidOperationException(); } XmlElement signedInfo = originalDoc.CreateElement("SignedInfo", SecurityConstants.XMLDSIG_URI); signature.AppendChild(signedInfo); XmlElement canonicalizationMethod = originalDoc.CreateElement("CanonicalizationMethod", SecurityConstants.XMLDSIG_URI); canonicalizationMethod.SetAttribute("Algorithm", SecurityConstants.XMLDSIG_URI_C14N); signedInfo.AppendChild(canonicalizationMethod); XmlElement signatureMethod = originalDoc.CreateElement("SignatureMethod", SecurityConstants.XMLDSIG_URI); if (externalSignature.GetEncryptionAlgorithm().Equals(SecurityConstants.RSA)) { signatureMethod.SetAttribute("Algorithm", SecurityConstants.XMLDSIG_URI_RSA_SHA1); } else if (externalSignature.GetEncryptionAlgorithm().Equals(SecurityConstants.DSA)) { signatureMethod.SetAttribute("Algorithm", SecurityConstants.XMLDSIG_URI_DSA_SHA1); } signedInfo.AppendChild(signatureMethod); foreach (XmlElement reference in references) { signedInfo.AppendChild(reference); } //if append Signature to original document upper - reference digest will be incorrect. originalDoc.DocumentElement.AppendChild(signature); XmlElement signedInfoDigest = (XmlElement)signedInfo.CloneNode(true); NormalizeNamespaces(signedInfo.CreateNavigator(), signedInfoDigest.CreateNavigator()); XmlDocument signedInfoDoc = new XmlDocument(originalDoc.NameTable); signedInfoDoc.LoadXml(signedInfoDigest.OuterXml); byte[] byteRange = CalculateC14nByteRange(signedInfoDoc); //Sign with ExternalSignature String valueBase64 = Convert.ToBase64String(externalSignature.Sign(byteRange)); XmlElement signatureValue = originalDoc.CreateElement("SignatureValue", SecurityConstants.XMLDSIG_URI); signatureValue.AppendChild(originalDoc.CreateTextNode(valueBase64)); signature.AppendChild(signatureValue); if (keyInfo != null) { XmlElement keyInfoElement = originalDoc.CreateElement("KeyInfo", SecurityConstants.XMLDSIG_URI); keyInfoElement.AppendChild(originalDoc.ImportNode(keyInfo.GetXml(), true)); signature.AppendChild(keyInfoElement); } if (dsObject != null) { signature.AppendChild(dsObject); } xmlLocator.SetDocument(originalDoc); }
/** * 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); }
private static void Sign(XmlElement signature, IXmlLocator xmlLocator, IExternalSignature externalSignature, List<XmlElement> references, XmlElement dsObject, KeyInfoClause keyInfo) { XmlDocument originalDoc = xmlLocator.GetDocument(); if (signature == null) throw new InvalidOperationException(); XmlElement signedInfo = originalDoc.CreateElement("SignedInfo", SecurityConstants.XMLDSIG_URI); signature.AppendChild(signedInfo); XmlElement canonicalizationMethod = originalDoc.CreateElement("CanonicalizationMethod", SecurityConstants.XMLDSIG_URI); canonicalizationMethod.SetAttribute("Algorithm", SecurityConstants.XMLDSIG_URI_C14N); signedInfo.AppendChild(canonicalizationMethod); XmlElement signatureMethod = originalDoc.CreateElement("SignatureMethod", SecurityConstants.XMLDSIG_URI); if(externalSignature.GetEncryptionAlgorithm().Equals(SecurityConstants.RSA)) signatureMethod.SetAttribute("Algorithm", SecurityConstants.XMLDSIG_URI_RSA_SHA1); else if(externalSignature.GetEncryptionAlgorithm().Equals(SecurityConstants.DSA)) signatureMethod.SetAttribute("Algorithm", SecurityConstants.XMLDSIG_URI_DSA_SHA1); signedInfo.AppendChild(signatureMethod); foreach (XmlElement reference in references) signedInfo.AppendChild(reference); //if append Signature to original document upper - reference digest will be incorrect. originalDoc.DocumentElement.AppendChild(signature); XmlElement signedInfoDigest = (XmlElement)signedInfo.CloneNode(true); NormalizeNamespaces(signedInfo.CreateNavigator(), signedInfoDigest.CreateNavigator()); XmlDocument signedInfoDoc = new XmlDocument(originalDoc.NameTable); signedInfoDoc.LoadXml(signedInfoDigest.OuterXml); byte[] byteRange = CalculateC14nByteRange(signedInfoDoc); //Sign with ExternalSignature String valueBase64 = Convert.ToBase64String(externalSignature.Sign(byteRange)); XmlElement signatureValue = originalDoc.CreateElement("SignatureValue", SecurityConstants.XMLDSIG_URI); signatureValue.AppendChild(originalDoc.CreateTextNode(valueBase64)); signature.AppendChild(signatureValue); if(keyInfo != null) { XmlElement keyInfoElement = originalDoc.CreateElement("KeyInfo", SecurityConstants.XMLDSIG_URI); keyInfoElement.AppendChild(originalDoc.ImportNode(keyInfo.GetXml(), true)); signature.AppendChild(keyInfoElement); } if (dsObject != null) signature.AppendChild(dsObject); xmlLocator.SetDocument(originalDoc); }
/// <summary>Signs the document using the detached mode, CMS or CAdES equivalent.</summary> /// <remarks> /// Signs the document using the detached mode, CMS or CAdES equivalent. /// <br /><br /> /// NOTE: This method closes the underlying pdf document. This means, that current instance /// of PdfSigner cannot be used after this method call. /// </remarks> /// <param name="externalSignature">the interface providing the actual signing</param> /// <param name="chain">the certificate chain</param> /// <param name="crlList">the CRL list</param> /// <param name="ocspClient">the OCSP client</param> /// <param name="tsaClient">the Timestamp client</param> /// <param name="externalDigest">an implementation that provides the digest</param> /// <param name="estimatedSize">the reserved size for the signature. It will be estimated if 0</param> /// <param name="sigtype">Either Signature.CMS or Signature.CADES</param> /// <exception cref="System.IO.IOException"/> /// <exception cref="Org.BouncyCastle.Security.GeneralSecurityException"/> public virtual void SignDetached(IExternalSignature externalSignature, X509Certificate[] chain, ICollection <ICrlClient> crlList, IOcspClient ocspClient, ITSAClient tsaClient, int estimatedSize, PdfSigner.CryptoStandard sigtype) { if (closed) { throw new PdfException(PdfException.ThisInstanceOfPdfSignerAlreadyClosed); } ICollection <byte[]> crlBytes = null; int i = 0; while (crlBytes == null && i < chain.Length) { crlBytes = ProcessCrl(chain[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; } } PdfSignatureAppearance appearance = GetSignatureAppearance(); appearance.SetCertificate(chain[0]); if (sigtype == PdfSigner.CryptoStandard.CADES) { AddDeveloperExtension(PdfDeveloperExtension.ESIC_1_7_EXTENSIONLEVEL2); } PdfSignature dic = new PdfSignature(PdfName.Adobe_PPKLite, sigtype == PdfSigner.CryptoStandard.CADES ? PdfName .ETSI_CAdES_DETACHED : PdfName.Adbe_pkcs7_detached); dic.SetReason(appearance.GetReason()); dic.SetLocation(appearance.GetLocation()); dic.SetSignatureCreator(appearance.GetSignatureCreator()); dic.SetContact(appearance.GetContact()); dic.SetDate(new PdfDate(GetSignDate())); // time-stamp will over-rule this cryptoDictionary = dic; IDictionary <PdfName, int?> exc = new Dictionary <PdfName, int?>(); exc[PdfName.Contents] = estimatedSize * 2 + 2; PreClose(exc); String hashAlgorithm = externalSignature.GetHashAlgorithm(); PdfPKCS7 sgn = new PdfPKCS7((ICipherParameters)null, chain, hashAlgorithm, false); Stream data = GetRangeStream(); byte[] hash = DigestAlgorithms.Digest(data, SignUtils.GetMessageDigest(hashAlgorithm)); byte[] ocsp = null; if (chain.Length >= 2 && ocspClient != null) { ocsp = ocspClient.GetEncoded((X509Certificate)chain[0], (X509Certificate)chain[1], null); } byte[] sh = sgn.GetAuthenticatedAttributeBytes(hash, ocsp, crlBytes, sigtype); byte[] extSignature = externalSignature.Sign(sh); sgn.SetExternalDigest(extSignature, null, externalSignature.GetEncryptionAlgorithm()); byte[] encodedSig = sgn.GetEncodedPKCS7(hash, tsaClient, ocsp, crlBytes, sigtype); if (estimatedSize < encodedSig.Length) { throw new System.IO.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)); Close(dic2); closed = true; }