Exemplo n.º 1
0
        public static byte[] ComputeValueOfElementList(XadesSignedXml xadesSignedXml, ArrayList elementXpaths)
        {
            XmlElement          signatureElement    = xadesSignedXml.GetSignatureElement();
            List <XmlAttribute> allNamespaces       = xadesSignedXml.GetAllNamespaces(signatureElement);
            XmlDocument         ownerDocument       = signatureElement.OwnerDocument;
            XmlNamespaceManager xmlNamespaceManager = new XmlNamespaceManager(ownerDocument.NameTable);

            xmlNamespaceManager.AddNamespace("ds", "http://www.w3.org/2000/09/xmldsig#");
            xmlNamespaceManager.AddNamespace("xades", "http://uri.etsi.org/01903/v1.3.2#");
            using (MemoryStream memoryStream = new MemoryStream())
            {
                foreach (string elementXpath in elementXpaths)
                {
                    XmlNodeList xmlNodeList = signatureElement.SelectNodes(elementXpath, xmlNamespaceManager);
                    if (xmlNodeList.Count == 0)
                    {
                        throw new CryptographicException("Element " + elementXpath + " not found while calculating hash");
                    }
                    foreach (XmlNode item in xmlNodeList)
                    {
                        XmlElement xmlElement = (XmlElement)item.Clone();
                        xmlElement.SetAttribute("xmlns:" + XadesSignedXml.XmlDSigPrefix, "http://www.w3.org/2000/09/xmldsig#");
                        foreach (XmlAttribute item2 in allNamespaces)
                        {
                            xmlElement.SetAttribute(item2.Name, item2.Value);
                        }
                        byte[] array = ApplyTransform(xmlElement, new XmlDsigC14NTransform());
                        memoryStream.Write(array, 0, array.Length);
                    }
                }
                return(memoryStream.ToArray());
            }
        }
        private void SetSignatureId(XadesSignedXml xadesSignedXml)
        {
            string text = Guid.NewGuid().ToString();

            xadesSignedXml.Signature.Id     = "xmldsig-ab2df1fb-1819-413d-8b8c-79e9ed75638a";
            xadesSignedXml.SignatureValueId = xadesSignedXml.Signature.Id + "-sigvalue";
        }
        private static void InjectSignatureToOriginalDoc(XadesSignedXml signedXml, XmlDocument originalDoc)
        {
            var xmlSig = signedXml.GetXml();
            var signedDataContainer = signedXml.GetIdElement(originalDoc, "signed-data-container");

            signedDataContainer?.InsertBefore(originalDoc.ImportNode(xmlSig, true), signedDataContainer.FirstChild);
        }
Exemplo n.º 4
0
        /// <exception cref="System.IO.IOException"></exception>
        public virtual Document ExtendSignature(object signatureId, Document document, Document
                                                originalData, SignatureParameters parameters)
        {
            if (this.tspSource == null)
            {
                throw new ConfigurationException(ConfigurationException.MSG.CONFIGURE_TSP_SERVER);
            }

            XmlDocument    envelopedSignatureXmlDocument;
            XmlDocument    xadesDocument;
            XmlElement     signature;
            XadesSignedXml xadesSignedXml;

            xadesDocument = XmlUtils.ToXmlDocument(document);
            xadesDocument.PreserveWhitespace = true;
            xadesDocument.Load(document.OpenStream());

            xadesSignedXml = new XadesSignedXml(xadesDocument.DocumentElement); //Needed if it is a enveloped signature document

            signature = xadesSignedXml.GetIdElement(xadesDocument, (string)signatureId);

            xadesSignedXml.LoadXml(signature);

            ExtendSignatureTag(xadesSignedXml);

            envelopedSignatureXmlDocument = XmlUtils.ToXmlDocument(originalData);
            return(XmlUtils.ToDocument(envelopedSignatureXmlDocument, xadesSignedXml));
        }
        /// <summary>
        /// Establece el identificador para la firma
        /// </summary>
        private void SetSignatureId(XadesSignedXml xadesSignedXml)
        {
            string id = Guid.NewGuid().ToString();

            xadesSignedXml.Signature.Id     = "Signature-" + id;
            xadesSignedXml.SignatureValueId = "SignatureValue-" + id;
        }
Exemplo n.º 6
0
        private void RequestTimeStamp(XadesSignedXml xadesSignedXml)
        {
            TimeStamp signatureTimeStamp;
            ArrayList signatureValueElementXpaths;

            byte[] signatureValueHash;
            byte[] tsaTimeStamp;

            signatureValueElementXpaths = new ArrayList();
            signatureValueElementXpaths.Add("ds:SignatureValue");
            signatureValueHash = ComputeHashValueOfElementList(xadesSignedXml.GetXml(), signatureValueElementXpaths);

            //jbonilla
            tsaTimeStamp = this.tspSource.GetTimeStampToken(signatureValueHash);

            signatureTimeStamp = new TimeStamp("SignatureTimeStamp");
            //signatureTimeStamp.EncapsulatedTimeStamp.Id = "SignatureTimeStamp" + this.uid;
            signatureTimeStamp.EncapsulatedTimeStamp.PkiData    = tsaTimeStamp;
            signatureTimeStamp.CanonicalizationMethod.Algorithm = SignedXml.XmlDsigExcC14NTransformUrl;

            //jbonilla Deprecated
            //HashDataInfo hashDataInfo = new HashDataInfo();
            //hashDataInfo.UriAttribute = "#" + elementIdValues[0];
            //signatureTimeStamp.HashDataInfoCollection.Add(hashDataInfo);

            UnsignedProperties unsignedProperties = xadesSignedXml.UnsignedProperties;

            unsignedProperties.UnsignedSignatureProperties.SignatureTimeStampCollection.Add(signatureTimeStamp);
            xadesSignedXml.UnsignedProperties = unsignedProperties;

            //TODO jbonilla - Delete?
            XmlElement xml  = xadesSignedXml.XadesObject.GetXml();
            XmlElement xml1 = xadesSignedXml.GetXml();
        }
Exemplo n.º 7
0
        /// <summary>
        /// Construye el documento enveloped
        /// </summary>
        private void CreateEnvelopedDocument()
        {
            Reference reference = new Reference();

            _xadesSignedXml = new XadesSignedXml(_document);

            reference.Id  = "Reference-" + Guid.NewGuid().ToString();
            reference.Uri = "";

            for (int i = 0; i < _document.DocumentElement.Attributes.Count; i++)
            {
                if (_document.DocumentElement.Attributes[i].Name.Equals("id", StringComparison.InvariantCultureIgnoreCase))
                {
                    reference.Uri = "#" + _document.DocumentElement.Attributes[i].Value;
                    break;
                }
            }

            XmlDsigEnvelopedSignatureTransform xmlDsigEnvelopedSignatureTransform = new XmlDsigEnvelopedSignatureTransform();

            reference.AddTransform(xmlDsigEnvelopedSignatureTransform);

            _objectReference = reference.Id;

            _xadesSignedXml.AddReference(reference);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Carga el documento XML especificado y establece para firmar el elemento especificado en elementId
        /// </summary>
        /// <param name="xmlDocument"></param>
        /// <param name="elementId"></param>
        /// <param name="mimeType"></param>
        public void SetContentInternallyDetached(XmlDocument xmlDocument, string elementId, string mimeType)
        {
            _document = (XmlDocument)xmlDocument.Clone();
            _document.PreserveWhitespace = true;

            Reference reference = new Reference();

            reference.Uri = "#" + elementId;
            reference.Id  = "Reference-" + Guid.NewGuid().ToString();

            _objectReference = reference.Id;
            _mimeType        = mimeType;

            if (mimeType == "text/xml")
            {
                XmlDsigC14NTransform transform = new XmlDsigC14NTransform();
                reference.AddTransform(transform);
            }
            else
            {
                XmlDsigBase64Transform transform = new XmlDsigBase64Transform();
                reference.AddTransform(transform);
            }

            _xadesSignedXml = new XadesSignedXml(_document);

            _xadesSignedXml.AddReference(reference);
        }
        private IEnumerable <X509Certificate2> GetCandidateCertificates(XadesSignedXml signedXml)
        {
            var certificates = ExtractCertificates(signedXml).ToArray();

            if (certificates.Length == 0)
            {
                throw new InvalidOperationException("Элемент KeyInfo.X509Data.X509Certificate не заполнен или отсутствует");
            }
            var certInfosCollection = signedXml.SignedSignatureProperties.SigningCertificate.CertCollection;

            if (certInfosCollection == null)
            {
                throw new InvalidOperationException("Элемент xades:SigningCertificate не заполнен или отсутствует");
            }
            var certInfos = certInfosCollection.OfType <Cert>().ToArray();

            foreach (var certificate in certificates)
            {
                var isCertificateMatch = certInfos.Any(certInfo => IsCertificateMatchCertInfo(certificate, certInfo));
                if (isCertificateMatch)
                {
                    yield return(certificate);
                }
            }
        }
Exemplo n.º 10
0
        protected internal override void ExtendSignatureTag(XadesSignedXml xadesSignedXml)
        {
            base.ExtendSignatureTag(xadesSignedXml);

            X509Certificate signingCertificate = DotNetUtilities.FromX509Certificate(
                xadesSignedXml.GetSigningCertificate());

            DateTime signingTime = xadesSignedXml.XadesObject.QualifyingProperties
                                   .SignedProperties.SignedSignatureProperties.SigningTime;

            ValidationContext ctx = certificateVerifier.ValidateCertificate(signingCertificate
                                                                            , signingTime, new XAdESCertificateSource(xadesSignedXml.GetXml(), false), null, null);

            UnsignedProperties unsignedProperties = xadesSignedXml.UnsignedProperties;

            var completeCertificateRefs = new CompleteCertificateRefs();

            IncorporateCertificateRefs(completeCertificateRefs, ctx);
            unsignedProperties.UnsignedSignatureProperties.CompleteCertificateRefs = completeCertificateRefs;

            var completeRevocationRefs = new CompleteRevocationRefs();

            IncorporateOCSPRefs(completeRevocationRefs, ctx);
            IncorporateCRLRefs(completeRevocationRefs, ctx);
            unsignedProperties.UnsignedSignatureProperties.CompleteRevocationRefs = completeRevocationRefs;

            xadesSignedXml.UnsignedProperties = unsignedProperties;
        }
Exemplo n.º 11
0
    public static XmlElement SignWithXAdES(X509Certificate2 signingCertificate, XmlDocument xmlDocument)
    {
        var signedXml = new XadesSignedXml(xmlDocument);

        signedXml.Signature.Id = SignatureId;
        signedXml.SigningKey   = signingCertificate.PrivateKey;

        var signatureReference = new Reference {
            Uri = "",
        };

        signatureReference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
        signedXml.AddReference(signatureReference);

        var keyInfo = new KeyInfo();

        keyInfo.AddClause(new KeyInfoX509Data(signingCertificate));
        signedXml.KeyInfo = keyInfo;

        AddXAdESProperties(xmlDocument, signedXml, signingCertificate);

        signedXml.ComputeSignature();

        return(signedXml.GetXml());
    }
Exemplo n.º 12
0
        public static XadesSignedXml GetXadesSignedXml(SigningKeyProvider provider, XmlDocument originalDoc, string signatureid)
        {
            var signedXml = new XadesSignedXml(originalDoc)
            {
                SigningKey = provider.SigningKey
            };

            signedXml.Signature.Id     = signatureid;
            signedXml.SignatureValueId = String.Format("{0}-sigvalue", signatureid);

            var reference = new Reference
            {
                Uri          = "#signed-data-container",
                DigestMethod = provider.DigestMethod,
                Id           = String.Format("{0}-ref0", signatureid)
            };

            reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
            reference.AddTransform(new XmlDsigExcC14NTransform());
            signedXml.AddReference(reference);

            signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigCanonicalizationUrl;
            signedXml.SignedInfo.SignatureMethod        = provider.SignatureMethod;

            return(signedXml);
        }
Exemplo n.º 13
0
        public static void InjectSignatureTo(this XadesSignedXml signedXml, XmlDocument originalDoc)
        {
            var signatureElement       = signedXml.GetXml();
            var importSignatureElement = originalDoc.ImportNode(signatureElement, true);
            var signedDataContainer    = signedXml.GetIdElement(originalDoc, signedXml.SignedElementId);

            signedDataContainer.InsertBefore(importSignatureElement, signedDataContainer.FirstChild);
        }
        public X509Certificate2 GetSignatureCertificate(XadesSignedXml signedXml)
        {
            var candidates = GetCandidateCertificates(signedXml).ToArray();

            if (!candidates.Any())
            {
                throw new InvalidOperationException("Не найдено ни одного сертификата, обозначенного в xades:SigningCertificate");
            }
            return(FindMatchedCertificate(signedXml, candidates));
        }
Exemplo n.º 15
0
        /// <summary>
        /// Añade una firma al documento
        /// </summary>
        /// <param name="certificate"></param>
        /// <param name="signMethod"></param>
        public void CoSign(X509Certificate2 certificate, SignMethod?signMethod = null)
        {
            if (_xadesSignedXml == null)
            {
                throw new Exception("No hay ninguna firma XADES creada previamente.");
            }

            if (certificate == null)
            {
                throw new Exception("Es necesario un certificado válido para la firma.");
            }

            Reference refContent = _xadesSignedXml.SignedInfo.References[0] as Reference;

            if (refContent == null)
            {
                throw new Exception("No se ha podido encontrar la referencia del contenido firmado.");
            }

            if (_xadesSignedXml.XadesObject.QualifyingProperties.SignedProperties.SignedDataObjectProperties.DataObjectFormatCollection.Count > 0)
            {
                foreach (DataObjectFormat dof in _xadesSignedXml.XadesObject.QualifyingProperties.SignedProperties.SignedDataObjectProperties.DataObjectFormatCollection)
                {
                    if (dof.ObjectReferenceAttribute == ("#" + refContent.Id))
                    {
                        _mimeType = dof.MimeType;
                        break;
                    }
                }
            }

            var destination = _xadesSignedXml.GetSignatureElement().ParentNode;

            _xadesSignedXml = new XadesSignedXml(_document);

            refContent.Id = "Reference-" + Guid.NewGuid().ToString();
            _xadesSignedXml.AddReference(refContent);

            if (destination.NodeType != XmlNodeType.Document)
            {
                _xadesSignedXml.SignatureNodeDestination = (XmlElement)destination;
            }
            else
            {
                _xadesSignedXml.SignatureNodeDestination = ((XmlDocument)destination).DocumentElement;
            }

            _objectReference = refContent.Id;

            SetSignatureId();

            Sign(certificate, signMethod);
        }
Exemplo n.º 16
0
        /// <summary>
        /// Construye el documento enveloped
        /// </summary>
        private void CreateEnvelopedDocument()
        {
            Reference reference = new Reference();

            _xadesSignedXml = new XadesSignedXml(_document);

            reference.DigestMethod = "http://www.w3.org/2001/10/xml-exc-c14n#";
            reference.Id           = "r-id-1";
            reference.Type         = "";
            reference.Uri          = "";


            //for (int i = 0; i < _document.DocumentElement.Attributes.Count; i++)
            //{
            //    if (_document.DocumentElement.Attributes[i].Name.Equals("id", StringComparison.InvariantCultureIgnoreCase))
            //    {
            //        reference.Uri = "#" + _document.DocumentElement.Attributes[i].Value;
            //        break;
            //    }
            //}

            // ** XmlDsigEnvelopedSignatureTransform xmlDsigEnvelopedSignatureTransform = new XmlDsigEnvelopedSignatureTransform();
            //xmlDsigEnvelopedSignatureTransform.Algorithm = "http://www.w3.org/TR/1999/REC-xpath-19991116";



            XmlDocument doc       = new XmlDocument();
            XmlElement  xpathElem = doc.CreateElement("XPath");

            xpathElem.InnerText = "not(ancestor-or-self::ds:Signature)";
            XmlDsigXPathTransform xform = new XmlDsigXPathTransform();

            xform.LoadInnerXml(xpathElem.SelectNodes("."));
            xform.Algorithm = "http://www.w3.org/TR/1999/REC-xpath-19991116";
            //xform.PropagatedNamespaces.Add("xmlns:ds", "http://www.w3.org/2000/09/xmldsig#");

            reference.AddTransform(xform);

            XmlDsigExcC14NTransform transform = new XmlDsigExcC14NTransform();

            reference.AddTransform(transform);


            //reference.AddTransform(xmlDsigEnvelopedSignatureTransform);

            _objectReference = reference.Id;

            _xadesSignedXml.AddReference(reference);
        }
Exemplo n.º 17
0
        /// <summary>
        /// Obtiene el valor canonicalizado de los elementos especificados en elementXpaths
        /// </summary>
        /// <param name="xadesSignedXml"></param>
        /// <param name="elementXpaths"></param>
        /// <returns></returns>
        public static byte[] ComputeValueOfElementList(XadesSignedXml xadesSignedXml, ArrayList elementXpaths)
        {
            XmlDocument         xmlDocument;
            XmlNamespaceManager xmlNamespaceManager;
            XmlNodeList         searchXmlNodeList;

            var signatureXmlElement = xadesSignedXml.GetSignatureElement();
            var namespaces          = xadesSignedXml.GetAllNamespaces(signatureXmlElement);

            xmlDocument         = signatureXmlElement.OwnerDocument;
            xmlNamespaceManager = new XmlNamespaceManager(xmlDocument.NameTable);
            xmlNamespaceManager.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl);
            xmlNamespaceManager.AddNamespace("xades", XadesSignedXml.XadesNamespaceUri);

            using (MemoryStream msResult = new MemoryStream())
            {
                foreach (string elementXpath in elementXpaths)
                {
                    searchXmlNodeList = signatureXmlElement.SelectNodes(elementXpath, xmlNamespaceManager);

                    if (searchXmlNodeList.Count == 0)
                    {
                        throw new CryptographicException("Element " + elementXpath + " not found while calculating hash");
                    }

                    foreach (XmlNode xmlNode in searchXmlNodeList)
                    {
                        XmlAttribute dsNamespace = xmlDocument.CreateAttribute("xmlns:" + XadesSignedXml.XmlDSigPrefix);
                        dsNamespace.Value = XadesSignedXml.XmlDsigNamespaceUrl;
                        xmlNode.Attributes.Append(dsNamespace);

                        foreach (var attr in namespaces)
                        {
                            XmlAttribute attrNamespace = xmlDocument.CreateAttribute(attr.Name);
                            attrNamespace.Value = attr.Value;
                            xmlNode.Attributes.Append(attrNamespace);
                        }

                        byte[] canonicalizedElement = ApplyTransform((XmlElement)xmlNode, new XmlDsigC14NTransform());
                        msResult.Write(canonicalizedElement, 0, canonicalizedElement.Length);
                    }
                }

                return(msResult.ToArray());
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// Realiza el proceso de firmado
        /// </summary>
        /// <param name="certificate"></param>
        /// <param name="signMethod"></param>
        public void Sign(X509Certificate2 certificate, SignMethod?signMethod = null)
        {
            _mimeType = "application/octet-stream";

            if (certificate == null)
            {
                throw new Exception("Es necesario un certificado válido para la firma.");
            }

            if (signMethod.HasValue)
            {
                this.SignMethod = signMethod.Value;
            }

            if (!string.IsNullOrEmpty(_signatureId) && _document != null &&
                _document.SelectSingleNode("//*[@Id='" + _signatureId + "']") != null)
            {
                throw new Exception("El documento ya ha sido firmado, debe seleccionar otro método de firma.");
            }

            if (string.IsNullOrEmpty(_signatureId))
            {
                SetSignatureId();
            }

            _signCertificate = certificate;

            AddCertificateInfo();
            AddXadesInfo();

            foreach (Reference reference in _xadesSignedXml.SignedInfo.References)
            {
                reference.DigestMethod = _refsMethodUri;
            }

            _xadesSignedXml.SignedInfo.SignatureMethod = _signMethodUri;

            ComputeSignature();

            UpdateDocument();

            XmlNode xmlNode = _document.SelectSingleNode("//*[@Id='" + _signatureId + "']");

            _xadesSignedXml = new XadesSignedXml(_document);
            _xadesSignedXml.LoadXml((XmlElement)xmlNode);
        }
Exemplo n.º 19
0
        private void AddCertificateInfoToSignature(XadesSignedXml xadesSignedXml, SignatureParameters parameters)
        {
            var key = parameters.SigningCertificate.GetPublicKey();

            if (key is RsaKeyParameters)
            {
                RSACryptoServiceProvider rsaKey     = new RSACryptoServiceProvider();
                RSAParameters            RSAKeyInfo = new RSAParameters();

                //Set RSAKeyInfo to the public key values.
                RSAKeyInfo.Modulus  = ((RsaKeyParameters)key).Modulus.ToByteArray();
                RSAKeyInfo.Exponent = ((RsaKeyParameters)key).Exponent.ToByteArray();

                rsaKey.ImportParameters(RSAKeyInfo);

                xadesSignedXml.SigningKey = rsaKey;

                KeyInfo keyInfo = new KeyInfo();

                // ETSI TS 103 171 V2.1.1
                // 6.2.1 Placement of the signing certificate
                // "b) In order to facilitate path-building, generators should include in the same ds:KeyInfo/X509Data element as
                // in note a) all certificates not available to verifiers that can be used during path building."
                //keyInfo.AddClause(new KeyInfoX509Data(this.certificate));
                {
                    KeyInfoX509Data x509Data = new KeyInfoX509Data();
                    foreach (X509Certificate cert in parameters.CertificateChain)
                    {
                        x509Data.AddCertificate(DotNetUtilities.ToX509Certificate2(cert));
                        //TODO jbonilla validar más de uno?
                        //break;
                    }
                    keyInfo.AddClause(x509Data);
                }

                keyInfo.AddClause(new RSAKeyValue(rsaKey));

                xadesSignedXml.KeyInfo = keyInfo;
            }
            else
            {
                throw new ArgumentException("Only allowed RsaKeyParameters", "key");
            }
        }
Exemplo n.º 20
0
        public static Document ToDocument(XmlDocument originalDocument, XadesSignedXml xadesSignedXml)
        {
            XmlElement xmlElementToSave;

            originalDocument.DocumentElement.AppendChild(originalDocument.ImportNode(xadesSignedXml.GetXml(), true));
            xmlElementToSave = originalDocument.DocumentElement;

            XmlDocument xmlDocument = new XmlDocument();

            xmlDocument.PreserveWhitespace = true; //Needed
            xmlDocument.LoadXml(xmlElementToSave.OuterXml);

            MemoryStream buf = new MemoryStream();

            xmlDocument.Save(buf);
            buf.Seek(0, SeekOrigin.Begin);

            return(new InMemoryDocument(buf.ToArray()));
        }
Exemplo n.º 21
0
        public void Run()
        {
            /*
             * 1. Получаем сертификат от клиента
             * 2. Формируем объект xades из сертификата от клиента
             * 3. Подписываем исходное сообщение
             * 4. Вычисляем хеш от SignedInfo и отправляем его для подписи клиенту
             * 5. Изменяем подписанное сообщение - подменяем подпись
             */

            var originalDoc = new XmlDocument()
            {
                PreserveWhitespace = true
            };

            originalDoc.LoadXml(_xmlStr);

            // 1. Получаем сертификат от клиента
            XadesInfo xadesInfo = GetClientXadesInfo();

            // 2. Формируем объект xades из сертификата от клиента
            XadesSignedXml xadesSignedXml = GetXadesSignedXml(xadesInfo, originalDoc);

            // 3. Подписываем исходное сообщение серверным сертификатом
            xadesSignedXml.ComputeSignature();

            // 4. Вычисляем хеш от SignedInfo и отправляем его для подписи клиенту
            HashAlgorithm hash;

            xadesSignedXml.GetSignedInfoHash(out hash);

            var signature = _client.GetSignedHash(Convert.ToBase64String(hash.Hash));

            // 5. Изменяем подписанное сообщение - подменяем подпись
            xadesSignedXml.Signature.SignatureValue = Convert.FromBase64String(signature);

            GisSignatureHelper.InjectSignatureToOriginalDoc(xadesSignedXml, originalDoc);

            Console.WriteLine("Получившееся сообщение:");
            Console.WriteLine(originalDoc.OuterXml);

            Assert.IsFalse(originalDoc.OuterXml.Contains("unstructuredName"));
        }
        private IEnumerable <X509Certificate2> ExtractCertificates(XadesSignedXml signedXml)
        {
            var keyInfo = signedXml.KeyInfo;

            if (keyInfo == null || keyInfo.Count == 0)
            {
                throw new InvalidOperationException("Элемент KeyInfo не заполнен или отсутствует");
            }
            if (keyInfo.Count > 1)
            {
                throw new InvalidOperationException("Найдено более одного элемента KeyInfo");
            }
            var x509Data = keyInfo.OfType <KeyInfoX509Data>().FirstOrDefault();

            if (x509Data == null)
            {
                throw new InvalidOperationException("Элемент X509Data не заполнен или отсутствует");
            }
            return(x509Data.Certificates.OfType <X509Certificate2>());
        }
Exemplo n.º 23
0
        /// <summary>
        /// Inserta un documento para generar una firma externally detached.
        /// </summary>
        /// <param name="fileName"></param>
        public void SetContentExternallyDetached(string fileName)
        {
            Reference reference = new Reference();

            _document       = new XmlDocument();
            _xadesSignedXml = new XadesSignedXml();

            reference.Uri = "file://" + fileName.Replace("\\", "/");
            reference.Id  = "Reference-" + Guid.NewGuid().ToString();

            if (reference.Uri.EndsWith(".xml") || reference.Uri.EndsWith(".XML"))
            {
                _mimeType = "text/xml";
                reference.AddTransform(new XmlDsigC14NTransform());
            }

            _objectReference = reference.Id;

            _xadesSignedXml.AddReference(reference);
        }
Exemplo n.º 24
0
        private static XadesSignedXml CreateFromXmlDocument(XmlDocument envelopedSignatureXmlDocument)
        {
            XmlDsigEnvelopedSignatureTransform xmlDsigEnvelopedSignatureTransform;
            Reference reference;

            reference = new Reference();

            var xadesSignedXml = new XadesSignedXml(envelopedSignatureXmlDocument);

            reference.Uri = "";
            reference.Id  = "xml_ref_id";

            //TODO jbonilla - Parameter?
            //reference.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256";
            reference.DigestMethod = SignedXml.XmlDsigSHA1Url;

            // ETSI TS 103 171 V2.1.1
            // 6.2.4 Transforms within ds:Reference element
            {
                //XmlDsigC14NTransform xmlDsigC14NTransform = new XmlDsigC14NTransform();
                //reference.AddTransform(xmlDsigC14NTransform);
                xmlDsigEnvelopedSignatureTransform = new XmlDsigEnvelopedSignatureTransform();
                reference.AddTransform(xmlDsigEnvelopedSignatureTransform);

                //jbonilla - Para permitir multifirmas (co-firmas)
                Dictionary <string, string> namespaces = new Dictionary <string, string>();
                namespaces.Add("ds", "http://www.w3.org/2000/09/xmldsig#");
                var xmlDsigXPathTransform = CreateXPathTransform("not(ancestor-or-self::ds:Signature)", namespaces);
                reference.AddTransform(xmlDsigXPathTransform);
            }
            xadesSignedXml.AddReference(reference);

            // ETSI TS 103 171 V2.1.1
            // 6.2.2 Canonicalization of ds:SignedInfo element
            xadesSignedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigC14NTransformUrl;//"http://www.w3.org/2001/10/xml-exc-c14n#";

            //xadesSignedXml.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
            xadesSignedXml.SignedInfo.SignatureMethod = SignedXml.XmlDsigRSASHA1Url;

            return(xadesSignedXml);
        }
        private static XadesSignedXml GetXadesSignedXml(X509Certificate2 certificate, XmlDocument originalDoc, string signatureid, string privateKeyPassword)
        {
            var secureString = new SecureString();

            foreach (var ch in privateKeyPassword)
            {
                secureString.AppendChar(ch);
            }

            var provider = (Gost3410CryptoServiceProvider)certificate.PrivateKey;

            provider.SetContainerPassword(secureString);

            var signedXml = new XadesSignedXml(originalDoc)
            {
                SigningKey = provider
            };

            signedXml.Signature.Id     = signatureid;
            signedXml.SignatureValueId = $"{signatureid}-sigvalue";

            var reference = new Reference
            {
                Uri = "#signed-data-container",
#pragma warning disable 612
                DigestMethod = CPSignedXml.XmlDsigGost3411UrlObsolete,
#pragma warning restore 612
                Id = $"{signatureid}-ref0"
            };

            reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
            reference.AddTransform(new XmlDsigExcC14NTransform());
            signedXml.AddReference(reference);

            signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigCanonicalizationUrl;
#pragma warning disable 612
            signedXml.SignedInfo.SignatureMethod = CPSignedXml.XmlDsigGost3410UrlObsolete;
#pragma warning restore 612

            return(signedXml);
        }
Exemplo n.º 26
0
        /// <summary>
        /// Inserta un contenido XML para generar una firma enveloping.
        /// </summary>
        /// <param name="xmlDocument"></param>
        public void SetContentEveloping(XmlDocument xmlDocument)
        {
            Reference reference = new Reference();

            _xadesSignedXml = new XadesSignedXml();

            XmlDocument doc = (XmlDocument)xmlDocument.Clone();

            doc.PreserveWhitespace = true;

            if (doc.ChildNodes[0].NodeType == XmlNodeType.XmlDeclaration)
            {
                doc.RemoveChild(doc.ChildNodes[0]);
            }

            //Add an object
            string dataObjectId = "DataObject-" + Guid.NewGuid().ToString();

            System.Security.Cryptography.Xml.DataObject dataObject = new System.Security.Cryptography.Xml.DataObject();
            dataObject.Data = doc.ChildNodes;
            dataObject.Id   = dataObjectId;
            _xadesSignedXml.AddObject(dataObject);

            reference.Id   = "Reference-" + Guid.NewGuid().ToString();
            reference.Uri  = "#" + dataObjectId;
            reference.Type = SignedXml.XmlDsigNamespaceUrl + "Object";

            XmlDsigC14NTransform transform = new XmlDsigC14NTransform();

            reference.AddTransform(transform);

            _objectReference = reference.Id;
            _mimeType        = "text/xml";

            _xadesSignedXml.AddReference(reference);

            _document = null;
        }
Exemplo n.º 27
0
        private void InjectXadesXInformation(XadesSignedXml xadesSignedXml)
        {
            TimeStamp xadesXTimeStamp;
            ArrayList signatureValueElementXpaths;

            byte[] signatureValueHash;
            byte[] tsaTimeStamp;

            signatureValueElementXpaths = new ArrayList();

            signatureValueElementXpaths.Add("ds:Object/xsd:QualifyingProperties/xsd:UnsignedProperties/xsd:UnsignedSignatureProperties/xsd:CompleteCertificateRefs");
            signatureValueElementXpaths.Add("ds:Object/xsd:QualifyingProperties/xsd:UnsignedProperties/xsd:UnsignedSignatureProperties/xsd:CompleteRevocationRefs");

            signatureValueHash = ComputeHashValueOfElementList(xadesSignedXml.GetXml(), signatureValueElementXpaths);

            //jbonilla
            tsaTimeStamp    = this.tspSource.GetTimeStampToken(signatureValueHash);
            xadesXTimeStamp = new TimeStamp("RefsOnlyTimeStamp");

            xadesXTimeStamp.EncapsulatedTimeStamp.PkiData    = tsaTimeStamp;
            xadesXTimeStamp.CanonicalizationMethod.Algorithm = SignedXml.XmlDsigExcC14NTransformUrl;
            //xadesXTimeStamp.EncapsulatedTimeStamp.Id = "";

            //jbonilla Deprecated
            //foreach (string elementIdValue in elementIdValues)
            //{
            //    hashDataInfo = new HashDataInfo();
            //    hashDataInfo.UriAttribute = "#" + elementIdValue;
            //    xadesXTimeStamp.HashDataInfoCollection.Add(hashDataInfo);
            //}

            UnsignedProperties unsignedProperties = xadesSignedXml.UnsignedProperties;

            unsignedProperties.UnsignedSignatureProperties.RefsOnlyTimeStampFlag = true;
            unsignedProperties.UnsignedSignatureProperties.RefsOnlyTimeStampCollection.Add(xadesXTimeStamp);

            xadesSignedXml.UnsignedProperties = unsignedProperties;
        }
Exemplo n.º 28
0
 public static void InjectSignatureToOriginalDoc(XadesSignedXml signedXml, XmlDocument originalDoc)
 {
     var xmlSig = signedXml.GetXml();
     var signedDataContainer = signedXml.GetIdElement(originalDoc, "signed-data-container");
     signedDataContainer.InsertBefore(originalDoc.ImportNode(xmlSig, true), signedDataContainer.FirstChild);
 }
Exemplo n.º 29
0
        public static XadesSignedXml GetXadesSignedXml(X509Certificate2 certificate, XmlDocument originalDoc, string signatureid, string privateKeyPassword)
        {
            var secureString = new SecureString();
            foreach (var ch in privateKeyPassword)
                secureString.AppendChar(ch);

            var provider = (Gost3410CryptoServiceProvider)certificate.PrivateKey;
            provider.SetContainerPassword(secureString);

            var signedXml = new XadesSignedXml(originalDoc) { SigningKey = provider };

            signedXml.Signature.Id = signatureid;
            signedXml.SignatureValueId = String.Format("{0}-sigvalue", signatureid);

            var reference = new Reference
            {
                Uri = "#signed-data-container",
                DigestMethod = CPSignedXml.XmlDsigGost3411UrlObsolete,
                Id = String.Format("{0}-ref0", signatureid)
            };
            reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
            reference.AddTransform(new XmlDsigExcC14NTransform());
            signedXml.AddReference(reference);

            signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigCanonicalizationUrl;
            signedXml.SignedInfo.SignatureMethod = CPSignedXml.XmlDsigGost3410UrlObsolete;

            return signedXml;
        }
Exemplo n.º 30
0
 protected internal virtual void ExtendSignatureTag(XadesSignedXml xadesSignedXml)
 {
     RequestTimeStamp(xadesSignedXml);
 }
        /// <summary>
        /// Realiza la contrafirma de la firma actual
        /// </summary>
        /// <param name="sigDocument"></param>
        /// <param name="parameters"></param>
        public SignatureDocument CounterSign(SignatureDocument sigDocument, SignatureParameters parameters)
        {
            if (parameters.Signer == null)
            {
                throw new Exception("Es necesario un certificado válido para la firma.");
            }

            SignatureDocument.CheckSignatureDocument(sigDocument);

            SignatureDocument counterSigDocument = new SignatureDocument();

            counterSigDocument.Document = (XmlDocument)sigDocument.Document.Clone();
            counterSigDocument.Document.PreserveWhitespace = true;

            XadesSignedXml counterSignature = new XadesSignedXml(counterSigDocument.Document);

            SetSignatureId(counterSignature);

            counterSignature.SigningKey = parameters.Signer.SigningKey;

            _refContent      = new Reference();
            _refContent.Uri  = "#" + sigDocument.XadesSignature.SignatureValueId;
            _refContent.Id   = "Reference-" + Guid.NewGuid().ToString();
            _refContent.Type = "http://uri.etsi.org/01903#CountersignedSignature";
            _refContent.AddTransform(new XmlDsigC14NTransform());
            counterSignature.AddReference(_refContent);

            _dataFormat          = new DataObjectFormat();
            _dataFormat.MimeType = "text/xml";
            _dataFormat.Encoding = "UTF-8";

            KeyInfo keyInfo = new KeyInfo();

            keyInfo.Id = "KeyInfoId-" + counterSignature.Signature.Id;
            keyInfo.AddClause(new KeyInfoX509Data((X509Certificate)parameters.Signer.Certificate));
            keyInfo.AddClause(new RSAKeyValue((RSA)parameters.Signer.SigningKey));
            counterSignature.KeyInfo = keyInfo;

            Reference referenceKeyInfo = new Reference();

            referenceKeyInfo.Id  = "ReferenceKeyInfo-" + counterSignature.Signature.Id;
            referenceKeyInfo.Uri = "#KeyInfoId-" + counterSignature.Signature.Id;
            counterSignature.AddReference(referenceKeyInfo);

            XadesObject counterSignatureXadesObject = new XadesObject();

            counterSignatureXadesObject.Id = "CounterSignatureXadesObject-" + Guid.NewGuid().ToString();
            counterSignatureXadesObject.QualifyingProperties.Target = "#" + counterSignature.Signature.Id;
            counterSignatureXadesObject.QualifyingProperties.SignedProperties.Id = "SignedProperties-" + counterSignature.Signature.Id;

            AddSignatureProperties(counterSigDocument, counterSignatureXadesObject.QualifyingProperties.SignedProperties.SignedSignatureProperties,
                                   counterSignatureXadesObject.QualifyingProperties.SignedProperties.SignedDataObjectProperties,
                                   counterSignatureXadesObject.QualifyingProperties.UnsignedProperties.UnsignedSignatureProperties, parameters);

            counterSignature.AddXadesObject(counterSignatureXadesObject);

            foreach (Reference signReference in counterSignature.SignedInfo.References)
            {
                signReference.DigestMethod = parameters.DigestMethod.URI;
            }

            counterSignature.SignedInfo.SignatureMethod = parameters.SignatureMethod.URI;

            counterSignature.AddXadesNamespace = true;
            counterSignature.ComputeSignature();

            UnsignedProperties unsignedProperties = sigDocument.XadesSignature.UnsignedProperties;

            unsignedProperties.UnsignedSignatureProperties.CounterSignatureCollection.Add(counterSignature);
            sigDocument.XadesSignature.UnsignedProperties = unsignedProperties;

            UpdateXadesSignature(sigDocument);

            counterSigDocument.Document = (XmlDocument)sigDocument.Document.Clone();
            counterSigDocument.Document.PreserveWhitespace = true;

            XmlElement signatureElement = (XmlElement)sigDocument.Document.SelectSingleNode("//*[@Id='" + counterSignature.Signature.Id + "']");

            counterSigDocument.XadesSignature = new XadesSignedXml(counterSigDocument.Document);
            counterSigDocument.XadesSignature.LoadXml(signatureElement);

            return(counterSigDocument);
        }
Exemplo n.º 32
0
        /// <summary>
        /// Load state from an XML element
        /// </summary>
        /// <param name="xmlElement">XML element containing new state</param>
        /// <param name="counterSignedXmlElement">Element containing parent signature (needed if there are counter signatures)</param>
        public void LoadXml(System.Xml.XmlElement xmlElement, XmlElement counterSignedXmlElement)
        {
            XmlNamespaceManager xmlNamespaceManager;
            XmlNodeList         xmlNodeList;
            IEnumerator         enumerator;
            XmlElement          iterationXmlElement;
            XadesSignedXml      newXadesSignedXml;
            TimeStamp           newTimeStamp;
            XmlElement          counterSignatureElement;

            if (xmlElement == null)
            {
                throw new ArgumentNullException("xmlElement");
            }

            xmlNamespaceManager = new XmlNamespaceManager(xmlElement.OwnerDocument.NameTable);
            xmlNamespaceManager.AddNamespace("xades", XadesSignedXml.XadesNamespaceUri);
            xmlNamespaceManager.AddNamespace("xadesv141", XadesSignedXml.XadesNamespace141Uri);

            this.counterSignatureCollection.Clear();
            xmlNodeList = xmlElement.SelectNodes("xades:CounterSignature", xmlNamespaceManager);
            enumerator  = xmlNodeList.GetEnumerator();
            try
            {
                while (enumerator.MoveNext())
                {
                    iterationXmlElement = enumerator.Current as XmlElement;
                    if (iterationXmlElement != null)
                    {
                        if (counterSignedXmlElement != null)
                        {
                            newXadesSignedXml = new XadesSignedXml(counterSignedXmlElement);
                        }
                        else
                        {
                            newXadesSignedXml = new XadesSignedXml();
                        }
                        //Skip any whitespace at start
                        counterSignatureElement = null;
                        for (int childNodeCounter = 0; (childNodeCounter < iterationXmlElement.ChildNodes.Count) && (counterSignatureElement == null); childNodeCounter++)
                        {
                            if (iterationXmlElement.ChildNodes[childNodeCounter] is XmlElement)
                            {
                                counterSignatureElement = (XmlElement)iterationXmlElement.ChildNodes[childNodeCounter];
                            }
                        }
                        if (counterSignatureElement != null)
                        {
                            newXadesSignedXml.LoadXml(counterSignatureElement);
                            this.counterSignatureCollection.Add(newXadesSignedXml);
                        }
                        else
                        {
                            throw new CryptographicException("CounterSignature element does not contain signature");
                        }
                    }
                }
            }
            finally
            {
                IDisposable disposable = enumerator as IDisposable;
                if (disposable != null)
                {
                    disposable.Dispose();
                }
            }

            this.signatureTimeStampCollection.Clear();
            xmlNodeList = xmlElement.SelectNodes("xades:SignatureTimeStamp", xmlNamespaceManager);
            enumerator  = xmlNodeList.GetEnumerator();
            try
            {
                while (enumerator.MoveNext())
                {
                    iterationXmlElement = enumerator.Current as XmlElement;
                    if (iterationXmlElement != null)
                    {
                        newTimeStamp = new TimeStamp("SignatureTimeStamp");
                        newTimeStamp.LoadXml(iterationXmlElement);
                        this.signatureTimeStampCollection.Add(newTimeStamp);
                    }
                }
            }
            finally
            {
                IDisposable disposable = enumerator as IDisposable;
                if (disposable != null)
                {
                    disposable.Dispose();
                }
            }

            xmlNodeList = xmlElement.SelectNodes("xades:CompleteCertificateRefs", xmlNamespaceManager);
            if (xmlNodeList.Count != 0)
            {
                this.completeCertificateRefs = new CompleteCertificateRefs();
                this.completeCertificateRefs.LoadXml((XmlElement)xmlNodeList.Item(0));
            }
            else
            {
                this.completeCertificateRefs = null;
            }

            xmlNodeList = xmlElement.SelectNodes("xades:CompleteRevocationRefs", xmlNamespaceManager);
            if (xmlNodeList.Count != 0)
            {
                this.CompleteRevocationRefs = new CompleteRevocationRefs();
                this.CompleteRevocationRefs.LoadXml((XmlElement)xmlNodeList.Item(0));
            }
            else
            {
                this.completeRevocationRefs = null;
            }

            this.sigAndRefsTimeStampCollection.Clear();
            this.refsOnlyTimeStampCollection.Clear();

            xmlNodeList = xmlElement.SelectNodes("xades:SigAndRefsTimeStamp", xmlNamespaceManager);
            if (xmlNodeList.Count > 0)
            {
                this.refsOnlyTimeStampFlag = false;
                enumerator = xmlNodeList.GetEnumerator();
                try
                {
                    while (enumerator.MoveNext())
                    {
                        iterationXmlElement = enumerator.Current as XmlElement;
                        if (iterationXmlElement != null)
                        {
                            newTimeStamp = new TimeStamp("SigAndRefsTimeStamp");
                            newTimeStamp.LoadXml(iterationXmlElement);
                            this.sigAndRefsTimeStampCollection.Add(newTimeStamp);
                        }
                    }
                }
                finally
                {
                    IDisposable disposable = enumerator as IDisposable;
                    if (disposable != null)
                    {
                        disposable.Dispose();
                    }
                }
            }
            else
            {
                xmlNodeList = xmlElement.SelectNodes("xades:RefsOnlyTimeStamp", xmlNamespaceManager);
                if (xmlNodeList.Count > 0)
                {
                    this.refsOnlyTimeStampFlag = true;
                    enumerator = xmlNodeList.GetEnumerator();
                    try
                    {
                        while (enumerator.MoveNext())
                        {
                            iterationXmlElement = enumerator.Current as XmlElement;
                            if (iterationXmlElement != null)
                            {
                                newTimeStamp = new TimeStamp("RefsOnlyTimeStamp");
                                newTimeStamp.LoadXml(iterationXmlElement);
                                this.refsOnlyTimeStampCollection.Add(newTimeStamp);
                            }
                        }
                    }
                    finally
                    {
                        IDisposable disposable = enumerator as IDisposable;
                        if (disposable != null)
                        {
                            disposable.Dispose();
                        }
                    }
                }
                else
                {
                    this.refsOnlyTimeStampFlag = false;
                }
            }

            xmlNodeList = xmlElement.SelectNodes("xades:CertificateValues", xmlNamespaceManager);
            if (xmlNodeList.Count != 0)
            {
                this.certificateValues = new CertificateValues();
                this.certificateValues.LoadXml((XmlElement)xmlNodeList.Item(0));
            }
            else
            {
                this.certificateValues = null;
            }

            xmlNodeList = xmlElement.SelectNodes("xades:RevocationValues", xmlNamespaceManager);
            if (xmlNodeList.Count != 0)
            {
                this.revocationValues = new RevocationValues();
                this.revocationValues.LoadXml((XmlElement)xmlNodeList.Item(0));
            }
            else
            {
                this.revocationValues = null;
            }

            this.archiveTimeStampCollection.Clear();
            xmlNodeList = xmlElement.SelectNodes("xades:ArchiveTimeStamp", xmlNamespaceManager);

            xmlNodeList = xmlElement.SelectNodes("xadesv141:ArchiveTimeStamp", xmlNamespaceManager);

            enumerator = xmlNodeList.GetEnumerator();
            try
            {
                while (enumerator.MoveNext())
                {
                    iterationXmlElement = enumerator.Current as XmlElement;
                    if (iterationXmlElement != null)
                    {
                        newTimeStamp = new TimeStamp("ArchiveTimeStamp");
                        newTimeStamp.LoadXml(iterationXmlElement);
                        this.archiveTimeStampCollection.Add(newTimeStamp);
                    }
                }
            }
            finally
            {
                IDisposable disposable = enumerator as IDisposable;
                if (disposable != null)
                {
                    disposable.Dispose();
                }
            }

            xmlNodeList = xmlElement.SelectNodes("xadesv141:ArchiveTimeStamp", xmlNamespaceManager);

            enumerator = xmlNodeList.GetEnumerator();
            try
            {
                while (enumerator.MoveNext())
                {
                    iterationXmlElement = enumerator.Current as XmlElement;
                    if (iterationXmlElement != null)
                    {
                        newTimeStamp = new TimeStamp("ArchiveTimeStamp", "xadesv141", XadesSignedXml.XadesNamespace141Uri);
                        newTimeStamp.LoadXml(iterationXmlElement);
                        this.archiveTimeStampCollection.Add(newTimeStamp);
                    }
                }
            }
            finally
            {
                IDisposable disposable = enumerator as IDisposable;
                if (disposable != null)
                {
                    disposable.Dispose();
                }
            }
        }