Facade class for the XAdES signature library. The class inherits from the System.Security.Cryptography.Xml.SignedXml class and is backwards compatible with it, so this class can host xmldsig signatures and XAdES signatures. The property SignatureStandard will indicate the type of the signature: XMLDSIG or XAdES.
Inheritance: System.Security.Cryptography.Xml.SignedXml
Example #1
4
        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;

        }
Example #2
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();
            }
        }
Example #3
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());
        }
Example #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);
        }
Example #5
0
 protected internal virtual void ExtendSignatureTag(XadesSignedXml xadesSignedXml)
 {
     RequestTimeStamp(xadesSignedXml);
 }
Example #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();
        }
Example #7
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");
            }
        }
Example #8
0
        /// <summary>
        /// Inserta un documento para generar una firma internally detached.
        /// </summary>
        /// <param name="content"></param>
        /// <param name="mimeType"></param>
        public void SetContentInternallyDetached(byte[] content, string mimeType, string fileName = null)
        {
            _document = new XmlDocument();

            XmlElement rootElement = _document.CreateElement("DOCFIRMA");
            _document.AppendChild(rootElement);

            string id = "CONTENT-" + Guid.NewGuid().ToString();

            Reference reference = new Reference();

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

            _objectReference = reference.Id;
            _mimeType = mimeType;

            XmlElement contentElement = _document.CreateElement("CONTENT");

            if (mimeType == "text/xml")
            {
                XmlDocument doc = new XmlDocument();
                doc.PreserveWhitespace = true;
                doc.Load(new MemoryStream(content));

                contentElement.InnerXml = doc.DocumentElement.OuterXml;

                XmlDsigC14NTransform transform = new XmlDsigC14NTransform();
                reference.AddTransform(transform);
            }
            else if (mimeType == "hash/sha256")
            {
                contentElement.SetAttribute("Encoding", "http://www.w3.org/2000/09/xmldsig#base64");
                contentElement.SetAttribute("MimeType", mimeType);

                if (!string.IsNullOrEmpty(fileName))
                {
                    contentElement.SetAttribute("URI", Path.GetFileName(fileName));
                }

                using (SHA256 sha2 = SHA256.Create())
                {
                    contentElement.InnerText = Convert.ToBase64String(sha2.ComputeHash(content));
                }

                XmlDsigBase64Transform transform = new XmlDsigBase64Transform();
                reference.AddTransform(transform);
            }
            else
            {
                contentElement.SetAttribute("Encoding", "http://www.w3.org/2000/09/xmldsig#base64");
                contentElement.InnerText = Convert.ToBase64String(content);

                XmlDsigBase64Transform transform = new XmlDsigBase64Transform();
                reference.AddTransform(transform);
            }

            contentElement.SetAttribute("Id", id);

            rootElement.AppendChild(contentElement);

            _xadesSignedXml = new XadesSignedXml(_document);

            _xadesSignedXml.AddReference(reference);
        }
Example #9
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);
        }
Example #10
0
        /// <summary>
        /// Realiza la contrafirma de la firma actual
        /// </summary>
        /// <param name="certificate"></param>
        /// <param name="signMethod"></param>
        public void CounterSign(X509Certificate2 certificate, SignMethod? signMethod = null)
        {
            SetSignatureId();

            if (_xadesSignedXml == null)
            {
                throw new Exception("No hay ninguna firma XADES cargada previamente.");
            }

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

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

            _signCertificate = certificate;

            XadesSignedXml counterSignature = new XadesSignedXml(_document);

            SetCryptoServiceProvider();

            counterSignature.SigningKey = _rsaKey;

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

            KeyInfo keyInfo = new KeyInfo();
            keyInfo.Id = "KeyInfoId-" + _signatureId;
            keyInfo.AddClause(new KeyInfoX509Data((X509Certificate)_signCertificate));
            keyInfo.AddClause(new RSAKeyValue((RSA)_rsaKey));
            counterSignature.KeyInfo = keyInfo;

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

            counterSignature.Signature.Id = _signatureId;
            counterSignature.SignatureValueId = _signatureValueId;

            XadesObject counterSignatureXadesObject = new XadesObject();
            counterSignatureXadesObject.Id = "CounterSignatureXadesObject-" + Guid.NewGuid().ToString();
            counterSignatureXadesObject.QualifyingProperties.Target = "#" + _signatureId;
            counterSignatureXadesObject.QualifyingProperties.SignedProperties.Id = "SignedProperties-" + _signatureId;

            AddSignatureProperties(counterSignatureXadesObject.QualifyingProperties.SignedProperties.SignedSignatureProperties,
                counterSignatureXadesObject.QualifyingProperties.SignedProperties.SignedDataObjectProperties,
                counterSignatureXadesObject.QualifyingProperties.UnsignedProperties.UnsignedSignatureProperties,
                "text/xml", _signCertificate);

            counterSignature.AddXadesObject(counterSignatureXadesObject);

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

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

            UnsignedProperties unsignedProperties = _xadesSignedXml.UnsignedProperties;
            unsignedProperties.UnsignedSignatureProperties.CounterSignatureCollection.Add(counterSignature);
            _xadesSignedXml.UnsignedProperties = unsignedProperties;

            UpdateDocument();

            _xadesSignedXml = new XadesSignedXml(_document);

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

            _xadesSignedXml.LoadXml((XmlElement)xmlNode);
        }
Example #11
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 = null;
            //int certificateValuesCounter;
            CertificateValues certificateValues;
            EncapsulatedX509Certificate encapsulatedX509Certificate;
            RevocationValues revocationValues;
            CRLValue newCRLValue;
            OCSPValue newOCSPValue;

            unsignedProperties = xadesSignedXml.UnsignedProperties;

            //TODO jbonilla Validate certificate refs.
            {                
                unsignedProperties.UnsignedSignatureProperties.CertificateValues = new CertificateValues();
                certificateValues = unsignedProperties.UnsignedSignatureProperties.CertificateValues;
                //certificateValues.Id = this.certificateValuesIdTextBox.Text;
                //certificateValuesCounter = 0;

                foreach (CertificateAndContext certificate in ctx.GetNeededCertificates())
                {
                    encapsulatedX509Certificate = new EncapsulatedX509Certificate();
                    //encapsulatedX509Certificate.Id = this.certificateValuesIdTextBox.Text + certificateValuesCounter.ToString();
                    encapsulatedX509Certificate.PkiData = certificate.GetCertificate().GetEncoded();
                    //certificateValuesCounter++;
                    certificateValues.EncapsulatedX509CertificateCollection.Add(encapsulatedX509Certificate);
                }             
            }
            
            unsignedProperties = xadesSignedXml.UnsignedProperties;
            unsignedProperties.UnsignedSignatureProperties.RevocationValues = new RevocationValues();
            revocationValues = unsignedProperties.UnsignedSignatureProperties.RevocationValues;
            //revocationValues.Id = this.revocationValuesIdTextBox.Text;           

            if (ctx.GetNeededOCSPResp().Count > 0)
            {
                foreach(BasicOcspResp ocsp in ctx.GetNeededOCSPResp())
                {
                    newOCSPValue = new OCSPValue();
                    newOCSPValue.PkiData = OCSPUtils.FromBasicToResp(ocsp).GetEncoded();
                    revocationValues.OCSPValues.OCSPValueCollection.Add(newOCSPValue);
                }               
            }

            if (ctx.GetNeededCRL().Count > 0)
            {
                foreach (X509Crl crl in ctx.GetNeededCRL())
                {
                    newCRLValue = new CRLValue();
                    newCRLValue.PkiData = crl.GetEncoded();
                    revocationValues.CRLValues.CRLValueCollection.Add(newCRLValue);
                }                
            }           

            xadesSignedXml.UnsignedProperties = unsignedProperties;
        }
		/// <summary>
		/// Add typed object to the collection
		/// </summary>
		/// <param name="objectToAdd">Typed object to be added to collection</param>
		/// <returns>The object that has been added to collection</returns>
		public XadesSignedXml Add(XadesSignedXml objectToAdd)
		{
			base.Add(objectToAdd);

			return objectToAdd;
		}
Example #13
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;   
        }
Example #14
0
        protected internal override void ExtendSignatureTag(XadesSignedXml xadesSignedXml)
        {
            base.ExtendSignatureTag(xadesSignedXml);

            InjectXadesXInformation(xadesSignedXml);
        }
Example #15
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);
        }
		/// <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("xsd", XadesSignedXml.XadesNamespaceUri);

			this.counterSignatureCollection.Clear();
			xmlNodeList = xmlElement.SelectNodes("xsd: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("xsd: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("xsd:CompleteCertificateRefs", xmlNamespaceManager);
			if (xmlNodeList.Count != 0)
			{
				this.completeCertificateRefs = new CompleteCertificateRefs();
				this.completeCertificateRefs.LoadXml((XmlElement)xmlNodeList.Item(0));
			}
			else
			{
				this.completeCertificateRefs = null;
			}

			xmlNodeList = xmlElement.SelectNodes("xsd: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("xsd: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("xsd: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("xsd:CertificateValues", xmlNamespaceManager);
			if (xmlNodeList.Count != 0)
			{
				this.certificateValues = new CertificateValues();
				this.certificateValues.LoadXml((XmlElement)xmlNodeList.Item(0));
			}
			else
			{
				this.certificateValues = null;
			}

			xmlNodeList = xmlElement.SelectNodes("xsd: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("xsd: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();
				}
			}
		}
Example #17
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);
        }
Example #18
0
        private void addCounterSignatureButton_Click(object sender, System.EventArgs e)
        {
            X509Certificate2 certificateForCounterSignature = this.LetUserChooseCertificate();
            if (certificateForCounterSignature != null)
            {
                this.xadesSignedXml.SignatureValueId = this.signatureValueIdTextBox.Text;

                XmlElement parentSignatureXmlElement = this.xadesSignedXml.GetXml();
                XmlDocument parentSignatureXmlDocument = new XmlDocument();
                parentSignatureXmlDocument.AppendChild(parentSignatureXmlDocument.ImportNode(parentSignatureXmlElement, true));

                XadesSignedXml counterSignature = new XadesSignedXml(parentSignatureXmlDocument);
                RSACryptoServiceProvider rsaKey = (RSACryptoServiceProvider) this.Certificate.PrivateKey;
                counterSignature.SigningKey = rsaKey;

                KeyInfo keyInfo = new KeyInfo();
                keyInfo.AddClause(new KeyInfoX509Data((X509Certificate) certificateForCounterSignature));
                keyInfo.AddClause(new RSAKeyValue(rsaKey));
                counterSignature.KeyInfo = keyInfo;

                Cert cert = new Cert();
                cert.IssuerSerial.X509IssuerName = certificateForCounterSignature.IssuerName.Name;
                cert.IssuerSerial.X509SerialNumber = certificateForCounterSignature.SerialNumber;
                cert.CertDigest.DigestMethod.Algorithm = SignedXml.XmlDsigSHA1Url;
                cert.CertDigest.DigestValue = certificateForCounterSignature.GetCertHash();

                counterSignature.Signature.Id = "CounterSignatureId";
                XadesObject counterSignatureXadesObject = new XadesObject();
                counterSignatureXadesObject.Id = "CounterSignatureXadesObjectId";
                counterSignatureXadesObject.QualifyingProperties.Target = "#CounterSignatureId";
                counterSignatureXadesObject.QualifyingProperties.SignedProperties.Id = "CounterSignatureSignedProperiesId";

                Reference newReference = new Reference();
                newReference.Uri = "#" + this.xadesSignedXml.SignatureValueId;
                counterSignature.AddReference(newReference);

                SignedSignatureProperties signedSignatureProperties = counterSignatureXadesObject.QualifyingProperties.SignedProperties.SignedSignatureProperties;
                signedSignatureProperties.SigningCertificate.CertCollection.Add(cert);
                signedSignatureProperties.SigningTime = DateTime.Parse(this.signingTimeTextBox.Text);
                signedSignatureProperties.SignaturePolicyIdentifier.SignaturePolicyImplied = true;
                counterSignature.AddXadesObject(counterSignatureXadesObject);

                counterSignature.ComputeSignature();

                UnsignedProperties unsignedProperties = this.xadesSignedXml.UnsignedProperties;
                unsignedProperties.UnsignedSignatureProperties.CounterSignatureCollection.Add(counterSignature);
                this.xadesSignedXml.UnsignedProperties = unsignedProperties;

                this.ShowSignature();
            }
        }
Example #19
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;
        }
Example #20
0
        private void addReferenceButton_Click(object sender, System.EventArgs e)
        {
            XmlDsigEnvelopedSignatureTransform xmlDsigEnvelopedSignatureTransform;
            Reference reference;

            reference = new Reference();
            if (this.envelopedSignatureRadioButton.Checked)
            {
                if (this.newSignatureCheckBox.Checked)
                {
                    this.envelopedSignatureXmlDocument = new XmlDocument();
                    this.documentDataObjectCounter = 1;
                }
                this.envelopedSignatureXmlDocument.PreserveWhitespace = true;
                this.envelopedSignatureXmlDocument.Load(this.envelopingDocumentTextBox.Text);
                this.xadesSignedXml = new XadesSignedXml(this.envelopedSignatureXmlDocument);

                reference.Uri = "";
                XmlDsigC14NTransform xmlDsigC14NTransform = new XmlDsigC14NTransform();
                reference.AddTransform(xmlDsigC14NTransform);
                xmlDsigEnvelopedSignatureTransform = new XmlDsigEnvelopedSignatureTransform();
                reference.AddTransform(xmlDsigEnvelopedSignatureTransform);
            }
            else
            {
                if (this.newSignatureCheckBox.Checked)
                {
                    this.xadesSignedXml = new XadesSignedXml();
                    this.documentDataObjectCounter = 1;
                }
                if (this.includedXmlRadioButton.Checked)
                {
                    reference.Uri = "#" + this.objectIdPrefixTextBox.Text + this.documentDataObjectCounter.ToString();
                    reference.Type = SignedXml.XmlDsigNamespaceUrl + "Object";

                    //Add an object
                    System.Security.Cryptography.Xml.DataObject dataObject = new System.Security.Cryptography.Xml.DataObject();
                    XmlDocument xmlDocument = new XmlDocument();
                    xmlDocument.PreserveWhitespace = true;
                    xmlDocument.LoadXml(this.includedXmltextBox.Text);
                    dataObject.Data = xmlDocument.ChildNodes;
                    dataObject.Id = this.objectIdPrefixTextBox.Text + this.documentDataObjectCounter.ToString();
                    this.xadesSignedXml.AddObject(dataObject);
                }
                else
                {
                    reference.Uri = this.externalDocumentUrlTextBox.Text;
                    if (reference.Uri.EndsWith(".xml") || reference.Uri.EndsWith(".XML"))
                    {
                        reference.AddTransform(new XmlDsigC14NTransform());
                    }
                }
            }
            this.xadesSignedXml.AddReference(reference);
            this.documentDataObjectCounter++;
            this.nextObjectIdSuffixLabel.Text = this.documentDataObjectCounter.ToString();
        }
Example #21
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);
        }
Example #22
0
        private void checkSignatureButton_Click(object sender, System.EventArgs e)
        {
            XmlDocument xmlDocument;
            XmlNodeList signatureNodeList;
            XadesCheckSignatureMasks composedMask;
            bool checkResult;

            try
            {
                this.signatureTypeLabel.Text = "...";
                this.checkSignatureLabel.Text = "...";
                this.Refresh();

                xmlDocument = new XmlDocument();
                xmlDocument.PreserveWhitespace = true;
                xmlDocument.Load(this.signatureFileToReadTextBox.Text);

                this.xadesSignedXml = new XadesSignedXml(xmlDocument.DocumentElement); //Needed if it is a enveloped signature document
                signatureNodeList = xmlDocument.GetElementsByTagName("Signature");
                if (signatureNodeList.Count == 0)
                {
                    signatureNodeList = xmlDocument.GetElementsByTagName("Signature", SignedXml.XmlDsigNamespaceUrl);
                }
                this.xadesSignedXml.LoadXml((XmlElement)signatureNodeList[0]);
                if (!this.readOnlyNoCheckcheckBox.Checked)
                {
                    composedMask = this.ComposeMask();
                    checkResult = this.xadesSignedXml.XadesCheckSignature(composedMask);
                    this.checkSignatureLabel.Text = checkResult.ToString();
                    if (checkResult == false)
                    {
                        this.checkSignatureLabel.ForeColor = Color.Red;
                    }
                    else
                    {
                        this.checkSignatureLabel.ForeColor = Color.Black;
                    }
                }
                this.signatureTypeLabel.Text = this.xadesSignedXml.SignatureStandard.ToString();
                this.verifyXmlRenderTree.RenderXmlNode(this.xadesSignedXml.GetXml());
            }
            catch (Exception exception)
            {
                this.signatureTypeLabel.Text = this.xadesSignedXml.SignatureStandard.ToString();
                if (exception.InnerException != null)
                {
                    MessageBox.Show("Exception: " + exception.Message + " -> " + exception.InnerException.Message);
                }
                else
                {
                    MessageBox.Show("Exception: " + exception.Message);
                }
            }
        }
Example #23
0
        /// <summary>
        /// Realiza el proceso de firmado
        /// </summary>
        /// <param name="certificate"></param>
        /// <param name="signMethod"></param>
        public void Sign(X509Certificate2 certificate, SignMethod? signMethod = null)
        {
            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);
        }
Example #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;
        }