public void FullChain () 
		{
			TransformChain chain = new TransformChain ();

			XmlDsigBase64Transform base64 = new XmlDsigBase64Transform ();
			chain.Add (base64);
			AssertEquals ("XmlDsigBase64Transform", base64, chain[0]);
			AssertEquals ("count 1", 1, chain.Count);

			XmlDsigC14NTransform c14n = new XmlDsigC14NTransform ();
			chain.Add (c14n);
			AssertEquals ("XmlDsigC14NTransform", c14n, chain[1]);
			AssertEquals ("count 2", 2, chain.Count);

			XmlDsigC14NWithCommentsTransform c14nc = new XmlDsigC14NWithCommentsTransform ();
			chain.Add (c14nc);
			AssertEquals ("XmlDsigC14NWithCommentsTransform", c14nc, chain[2]);
			AssertEquals ("count 3", 3, chain.Count);

			XmlDsigEnvelopedSignatureTransform esign = new XmlDsigEnvelopedSignatureTransform ();
			chain.Add (esign);
			AssertEquals ("XmlDsigEnvelopedSignatureTransform", esign, chain[3]);
			AssertEquals ("count 4", 4, chain.Count);

			XmlDsigXPathTransform xpath = new XmlDsigXPathTransform ();
			chain.Add (xpath);
			AssertEquals ("XmlDsigXPathTransform", xpath, chain[4]);
			AssertEquals ("count 5", 5, chain.Count);

			XmlDsigXsltTransform xslt = new XmlDsigXsltTransform ();
			chain.Add (xslt);
			AssertEquals ("XmlDsigXsltTransform", xslt, chain[5]);
			AssertEquals ("count 6", 6, chain.Count);
		}
		void CheckProperties (XmlDsigC14NTransform transform)
		{
			Type[] input = transform.InputTypes;
			Assert.IsTrue ((input.Length == 3), "Input #");
			// check presence of every supported input types
			bool istream = false;
			bool ixmldoc = false;
			bool ixmlnl = false;
			foreach (Type t in input) {
				if (t.ToString () == "System.IO.Stream")
					istream = true;
				if (t.ToString () == "System.Xml.XmlDocument")
					ixmldoc = true;
				if (t.ToString () == "System.Xml.XmlNodeList")
					ixmlnl = true;
			}
			Assert.IsTrue (istream, "Input Stream");
			Assert.IsTrue (ixmldoc, "Input XmlDocument");
			Assert.IsTrue (ixmlnl, "Input XmlNodeList");

			Type[] output = transform.OutputTypes;
			Assert.IsTrue ((output.Length == 1), "Output #");
			// check presence of every supported output types
			bool ostream = false;
			foreach (Type t in output) {
				if (t.ToString () == "System.IO.Stream")
					ostream = true;
			}
			Assert.IsTrue (ostream, "Output Stream");
		}
Example #3
0
 /// <summary>
 /// Compares all idml's in outputPath to make sure the content.xml and styles.xml are the same
 /// </summary>
 public static void AreEqual(string expectFullName, string outputFullName, string msg)
 {
     using (var expFl = new ZipFile(expectFullName))
     {
         var outFl = new ZipFile(outputFullName);                
         foreach (ZipEntry zipEntry in expFl)
         {
             //TODO: designmap.xml should be tested but \\MetadataPacketPreference should be ignored as it contains the creation date.
             if (!CheckFile(zipEntry.Name,"Stories,Spreads,Resources,MasterSpreads"))
                 continue;
             if (Path.GetExtension(zipEntry.Name) != ".xml")
                 continue;
             string outputEntry = new StreamReader(outFl.GetInputStream(outFl.GetEntry(zipEntry.Name).ZipFileIndex)).ReadToEnd();
             string expectEntry = new StreamReader(expFl.GetInputStream(expFl.GetEntry(zipEntry.Name).ZipFileIndex)).ReadToEnd();
             XmlDocument outputDocument = new XmlDocument();
             outputDocument.XmlResolver = FileStreamXmlResolver.GetNullResolver();
             outputDocument.LoadXml(outputEntry);
             XmlDocument expectDocument = new XmlDocument();
             outputDocument.XmlResolver = FileStreamXmlResolver.GetNullResolver();
             expectDocument.LoadXml(expectEntry);
             XmlDsigC14NTransform outputCanon = new XmlDsigC14NTransform();
             outputCanon.Resolver = new XmlUrlResolver();
             outputCanon.LoadInput(outputDocument);
             XmlDsigC14NTransform expectCanon = new XmlDsigC14NTransform();
             expectCanon.Resolver = new XmlUrlResolver();
             expectCanon.LoadInput(expectDocument);
             Stream outputStream = (Stream)outputCanon.GetOutput(typeof(Stream));
             Stream expectStream = (Stream)expectCanon.GetOutput(typeof(Stream));
             string errMessage = string.Format("{0}: {1} doesn't match", msg, zipEntry.Name);
             Assert.AreEqual(expectStream.Length, outputStream.Length, errMessage);
             FileAssert.AreEqual(expectStream, outputStream, errMessage);
         }
     }
 }
Example #4
0
		public void FullChain () 
		{
			TransformChain chain = new TransformChain ();

			XmlDsigBase64Transform base64 = new XmlDsigBase64Transform ();
			chain.Add (base64);
			Assert.AreEqual (base64, chain[0], "XmlDsigBase64Transform");
			Assert.AreEqual (1, chain.Count, "count 1");

			XmlDsigC14NTransform c14n = new XmlDsigC14NTransform ();
			chain.Add (c14n);
			Assert.AreEqual (c14n, chain[1], "XmlDsigC14NTransform");
			Assert.AreEqual (2, chain.Count, "count 2");

			XmlDsigC14NWithCommentsTransform c14nc = new XmlDsigC14NWithCommentsTransform ();
			chain.Add (c14nc);
			Assert.AreEqual (c14nc, chain[2], "XmlDsigC14NWithCommentsTransform");
			Assert.AreEqual (3, chain.Count, "count 3");

			XmlDsigEnvelopedSignatureTransform esign = new XmlDsigEnvelopedSignatureTransform ();
			chain.Add (esign);
			Assert.AreEqual (esign, chain[3], "XmlDsigEnvelopedSignatureTransform");
			Assert.AreEqual (4, chain.Count, "count 4");

			XmlDsigXPathTransform xpath = new XmlDsigXPathTransform ();
			chain.Add (xpath);
			Assert.AreEqual (xpath, chain[4], "XmlDsigXPathTransform");
			Assert.AreEqual (5, chain.Count, "count 5");

			XmlDsigXsltTransform xslt = new XmlDsigXsltTransform ();
			chain.Add (xslt);
			Assert.AreEqual (xslt, chain[5], "XmlDsigXsltTransform");
			Assert.AreEqual (6, chain.Count, "count 6");
		}
Example #5
0
 /// <summary>
 /// Compares all odt's in outputPath to make sure the content.xml and styles.xml are the same
 /// </summary>
 /// <param name="expectPath">expected output path</param>
 /// <param name="outputPath">output path</param>
 /// <param name="msg">message to display if mismatch</param>
 public static void AreEqual(string expectPath, string outputPath, string msg)
 {
     var outDi = new DirectoryInfo(outputPath);
     var expDi = new DirectoryInfo(expectPath);
     FileInfo[] outFi = outDi.GetFiles("*.od*");
     FileInfo[] expFi = expDi.GetFiles("*.od*");
     Assert.AreEqual(outFi.Length, expFi.Length, string.Format("{0} {1} odt found {2} expected", msg, outFi.Length, expFi.Length));
     foreach (FileInfo fi in outFi)
     {
         var outFl = new ZipFile(fi.FullName);
         var expFl = new ZipFile(Common.PathCombine(expectPath, fi.Name));
         foreach (string name in "content.xml,styles.xml".Split(','))
         {
             string outputEntry = new StreamReader(outFl.GetInputStream(outFl.GetEntry(name).ZipFileIndex)).ReadToEnd();
             string expectEntry = new StreamReader(expFl.GetInputStream(expFl.GetEntry(name).ZipFileIndex)).ReadToEnd();
             XmlDocument outputDocument = new XmlDocument();
             outputDocument.XmlResolver = FileStreamXmlResolver.GetNullResolver();
             outputDocument.LoadXml(outputEntry);
             XmlDocument expectDocument = new XmlDocument();
             expectDocument.XmlResolver = FileStreamXmlResolver.GetNullResolver();
             expectDocument.LoadXml(expectEntry);
             XmlDsigC14NTransform outputCanon = new XmlDsigC14NTransform();
             outputCanon.Resolver = new XmlUrlResolver();
             outputCanon.LoadInput(outputDocument);
             XmlDsigC14NTransform expectCanon = new XmlDsigC14NTransform();
             expectCanon.Resolver = new XmlUrlResolver();
             expectCanon.LoadInput(expectDocument);
             Stream outputStream = (Stream)outputCanon.GetOutput(typeof(Stream));
             Stream expectStream = (Stream)expectCanon.GetOutput(typeof(Stream));
             string errMessage = string.Format("{0}: {1} {2} doesn't match", msg, fi.Name, name);
             Assert.AreEqual(expectStream.Length, outputStream.Length, errMessage);
             FileAssert.AreEqual(expectStream, outputStream, errMessage);
         }
     }
 }
Example #6
0
        private byte[] canonicalize(XmlNode outerData, string signedInfoTransformAlg)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(outerData.InnerXml);

            var data = doc.DocumentElement;

            XmlDsigC14NTransform transform = new XmlDsigC14NTransform();
            transform.Algorithm = signedInfoTransformAlg;
            transform.LoadInput(doc);// =  data;

            var a = transform.GetOutput();
            var aa = a.ToString();

            var b = a as System.IO.Stream;

            b.Position = 0;
            byte[] buffer = new byte[b.Length];
            for (int totalBytesCopied = 0; totalBytesCopied < b.Length;)
                totalBytesCopied += b.Read(buffer, totalBytesCopied, Convert.ToInt32(b.Length) - totalBytesCopied);
            return buffer;

            //return System.Text.Encoding.UTF8.GetBytes(aa);
            //XmlDsigExcC14NTransform.
            //System.Security.Cryptography
            throw new NotImplementedException();
        }
Example #7
0
        /// <remarks>Sólo se implementan las transformadas de canonicalización</remarks>

        private Stream SignedInfoTransformed()
        {
            System.Security.Cryptography.Xml.Transform t = null;
            switch (signature.SignedInfo.CanonicalizationMethod)
            {
            case XmlSignatureConstants.XmlDsigC14NTransformUrl:
                t = new System.Security.Cryptography.Xml.XmlDsigC14NTransform();
                break;

            case XmlSignatureConstants.XmlDsigC14NWithCommentsTransformUrl:
                t = new System.Security.Cryptography.Xml.XmlDsigC14NWithCommentsTransform();
                break;

            case XmlSignatureConstants.XmlDsigExcC14NTransformUrl:
                t = new System.Security.Cryptography.Xml.XmlDsigExcC14NTransform(signature.SignedInfo.InclusiveNamespaces);
                break;

            case XmlSignatureConstants.XmlDsigExcC14NWithCommentsTransformUrl:
                t = new System.Security.Cryptography.Xml.XmlDsigExcC14NWithCommentsTransform();
                break;

            default:
                t = null;
                break;
            }
            if (t == null)
            {
                return(null);
            }

            XmlDocument doc = new XmlDocument();

            doc.PreserveWhitespace = true;

            XmlElement signatureNode = (XmlElement)envdoc.SelectSingleNode("//*[@Id='" + signature.Id + "']");

            if (signatureNode != null)
            {
                XmlNamespaceManager xmlnsManager = new XmlNamespaceManager(envdoc.NameTable);
                xmlnsManager.AddNamespace("ds", "http://www.w3.org/2000/09/xmldsig#");

                XmlNode signedInfoNode = signatureNode.SelectSingleNode("ds:SignedInfo", xmlnsManager);

                doc.LoadXml(signedInfoNode.OuterXml);
            }
            else
            {
                doc.LoadXml(signature.SignedInfo.GetXml().OuterXml);
            }

            var namespaces = GetAllNamespaces(signatureNode);

            foreach (var item in namespaces)
            {
                AddNameSpace(doc, doc.DocumentElement, item.Name, item.Value);
            }

            return(ApplyTransform(t, doc));
        }
		public SignedInfo() 
		{
			references = new ArrayList ();
			c14nMethod = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315";
#if NET_2_0	
			canonicalizationMethodObject = new XmlDsigC14NTransform ();
#endif
		}
Example #9
0
        public XmlDocument assinaturaXmlEnviar(XmlDocument _xml)
        {
            XmlDocument xmlDocAss = _xml;

            try
            {


                if (cert == null)
                    throw new Exception("Nao foi encontrado o certificado: " + config.configNFCe.NomeCertificadoDigital);

                Reference reference = new Reference();
                SignedXml docXML = new SignedXml(xmlDocAss);

                docXML.SigningKey = cert.PrivateKey;
                XmlAttributeCollection uri = xmlDocAss.GetElementsByTagName("infNFe").Item(0).Attributes;
                foreach (XmlAttribute atributo in uri)
                {
                    if (atributo.Name == "Id")
                        reference.Uri = "#" + atributo.InnerText;
                }

                XmlDsigEnvelopedSignatureTransform envelopedSigntature = new XmlDsigEnvelopedSignatureTransform();
                reference.AddTransform(envelopedSigntature);

                XmlDsigC14NTransform c14Transform = new XmlDsigC14NTransform();
                reference.AddTransform(c14Transform);
                docXML.AddReference(reference);

                KeyInfo keyInfo = new KeyInfo();
                keyInfo.AddClause(new KeyInfoX509Data(cert));

                docXML.KeyInfo = keyInfo;
                docXML.ComputeSignature();

                XmlElement xmlDigitalSignature = docXML.GetXml();

                foreach (var _nfe in xmlDocAss.GetElementsByTagName("NFe").Cast<XmlElement>())
                    _nfe.AppendChild(xmlDocAss.ImportNode(xmlDigitalSignature, true));


                xmlDocAss.PreserveWhitespace = true;
                return xmlDocAss;
            }

            catch (Exception e)
            {
                Utils.Logger.getInstance.error(e);
                return null;
                throw new Exception(e.ToString());
            }


        }
        public string AssinarComCertificado(string textXML, X509Certificate2 certificado)
        {
            try
            {
                string xmlString = textXML;

                XmlDocument doc = new XmlDocument();
                doc.PreserveWhitespace = false;
                doc.LoadXml(xmlString);

                Reference reference = new Reference();
                reference.Uri = "";

                XmlDocument documentoNovo = new XmlDocument();
                documentoNovo.LoadXml(doc.OuterXml);

                SignedXml signedXml = new SignedXml(documentoNovo);

                signedXml.SigningKey = certificado.PrivateKey;

                XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
                reference.AddTransform(env);

                XmlDsigC14NTransform c14 = new XmlDsigC14NTransform();
                reference.AddTransform(c14);

                signedXml.AddReference(reference);

                KeyInfo keyInfo = new KeyInfo();

                keyInfo.AddClause(new KeyInfoX509Data(certificado));

                signedXml.KeyInfo = keyInfo;
                signedXml.ComputeSignature();

                XmlElement xmlDigitalSignature = signedXml.GetXml();

                XmlNode sign = doc.ImportNode(xmlDigitalSignature, true);
                doc.ChildNodes.Item(0).AppendChild(sign);

                XmlDocument XMLDoc = new XmlDocument();
                XMLDoc.PreserveWhitespace = false;
                XMLDoc = doc;

                return XMLDoc.OuterXml;

            } catch (Exception error)
            {
                throw new Exception(error.Message);
            }
        }
Example #11
0
 /// <summary>
 /// Compares the XML file at expected path tand output path to make sure they are the same in terms of what matters to XML.
 /// </summary>
 /// <param name="expectPath">expected output path</param>
 /// <param name="outputPath">output path</param>
 /// <param name="msg">message to display if mismatch</param>
 public static void AreEqual(string expectPath, string outputPath, string msg)
 {
     XmlDocument outputDocument = Common.DeclareXMLDocument(false);
     outputDocument.Load(outputPath);
     XmlDocument expectDocument = Common.DeclareXMLDocument(false);
     expectDocument.Load(expectPath);
     XmlDsigC14NTransform outputCanon = new XmlDsigC14NTransform();
     outputCanon.Resolver = null;
     outputCanon.LoadInput(outputDocument);
     XmlDsigC14NTransform expectCanon = new XmlDsigC14NTransform();
     expectCanon.Resolver = null;
     expectCanon.LoadInput(expectDocument);
     Stream outputStream = (Stream)outputCanon.GetOutput(typeof(Stream));
     Stream expectStream = (Stream)expectCanon.GetOutput(typeof(Stream));
     FileAssert.AreEqual(expectStream, outputStream, msg);
 }
        public override string SignXml(XmlDocument Document)
        {
            // create detached envelope
            XmlDocument envelope = new XmlDocument();
            envelope.PreserveWhitespace = true;
            envelope.AppendChild(envelope.CreateElement("Envelope"));

            XmlElement message = envelope.CreateElement("Message");
            message.InnerXml = Document.DocumentElement.OuterXml;
            message.SetAttribute("Id", "MyObjectID");
            envelope.DocumentElement.AppendChild(message);

            SignedXmlWithId signedXml = new SignedXmlWithId(envelope);
            signedXml.SigningKey = manager.Certificate.PrivateKey;

            // Create a reference to be signed.
            Reference reference = new Reference();
            reference.Uri = "#MyObjectID";

            if (c14)
            {
                XmlDsigC14NTransform env = new XmlDsigC14NTransform();
                reference.AddTransform(env);
            }

            KeyInfo keyInfo = new KeyInfo();
            KeyInfoX509Data keyInfoData = new KeyInfoX509Data(manager.Certificate);
            keyInfo.AddClause(keyInfoData);
            signedXml.KeyInfo = keyInfo;

            // Add the reference to the SignedXml object.
            signedXml.AddReference(reference);

            // Compute the signature.
            signedXml.ComputeSignature();

            // Get the XML representation of the signature and save
            // it to an XmlElement object.
            XmlElement xmlDigitalSignature = signedXml.GetXml();

            envelope.DocumentElement.AppendChild(
               envelope.ImportNode(xmlDigitalSignature, true));

            return envelope.OuterXml;
        }
        public override string SignXml(XmlDocument Document)
        {
            SignedXmlWithId signedXml = new SignedXmlWithId(Document);
            signedXml.SigningKey = manager.Certificate.PrivateKey;

            KeyInfo keyInfo = new KeyInfo();
            KeyInfoX509Data keyInfoData = new KeyInfoX509Data(manager.Certificate);
            keyInfo.AddClause(keyInfoData);
            signedXml.KeyInfo = keyInfo;

            // the DataObject has to point to a XmlNodeList
            DataObject dataObject = new DataObject();
            dataObject.Id = "MyObjectID1";
            dataObject.Data =
               new CustomXmlNodeList(new[] { Document.DocumentElement });
            signedXml.AddObject(dataObject);

            // Add the reference to the SignedXml object.
            Reference reference = new Reference();
            reference.Uri = "#MyObjectID1";
            signedXml.AddReference(reference);

            // Create a reference to be signed.
            if (c14)
            {
                XmlDsigC14NTransform env = new XmlDsigC14NTransform();
                reference.AddTransform(env);
            }

            // Compute the signature.
            signedXml.ComputeSignature();

            // Get the XML representation of the signature and save
            // it to an XmlElement object.
            XmlElement xmlDigitalSignature = signedXml.GetXml();

            // create detached envelope
            XmlDocument envelope = new XmlDocument();
            envelope.AppendChild(envelope.CreateElement("Envelope"));

            envelope.DocumentElement.AppendChild(
               envelope.ImportNode(xmlDigitalSignature, true));

            return envelope.OuterXml;
        }
        public override string SignXml(XmlDocument Document)
        {
            SignedXmlWithId signedXml = new SignedXmlWithId(Document);
            signedXml.SigningKey = manager.Certificate.PrivateKey;

            // Create a reference to be signed.
            Reference reference = new Reference();
            reference.Uri = "";

            // Add an enveloped transformation to the reference.
            XmlDsigEnvelopedSignatureTransform env =
               new XmlDsigEnvelopedSignatureTransform(true);
            reference.AddTransform(env);

            if (c14)
            {
                XmlDsigC14NTransform c14t = new XmlDsigC14NTransform();
                reference.AddTransform(c14t);
            }

            KeyInfo keyInfo = new KeyInfo();
            KeyInfoX509Data keyInfoData = new KeyInfoX509Data(manager.Certificate);
            keyInfo.AddClause(keyInfoData);
            signedXml.KeyInfo = keyInfo;

            // Add the reference to the SignedXml object.
            signedXml.AddReference(reference);

            // Compute the signature.
            signedXml.ComputeSignature();

            // Get the XML representation of the signature and save
            // it to an XmlElement object.
            XmlElement xmlDigitalSignature = signedXml.GetXml();

            Document.DocumentElement.AppendChild(
                Document.ImportNode(xmlDigitalSignature, true));

            return Document.OuterXml;
        }
Example #15
0
        /// <summary>
        /// Signs an XML Document for a Saml Response
        /// </summary>
        /// <param name="xml"></param>
        /// <param name="cert2"></param>
        /// <param name="referenceId"></param>
        /// <returns></returns>
        public static XmlElement SignDoc(XmlDocument doc, X509Certificate2 cert2, string referenceId, string referenceValue)
        {
            SamlSignedXml sig = new SamlSignedXml(doc, referenceId);
            // Add the key to the SignedXml xmlDocument.
            sig.SigningKey = cert2.PrivateKey;

            // Create a reference to be signed.
            Reference reference = new Reference();

            reference.Uri = String.Empty;
            reference.Uri = "#" + referenceValue;

            // Add an enveloped transformation to the reference.
            XmlDsigEnvelopedSignatureTransform env = new
                XmlDsigEnvelopedSignatureTransform();
            XmlDsigC14NTransform env2 = new XmlDsigC14NTransform();

            reference.AddTransform(env);
            reference.AddTransform(env2);

            // Add the reference to the SignedXml object.
            sig.AddReference(reference);

            // Add an RSAKeyValue KeyInfo (optional; helps recipient find key to validate).
            KeyInfo keyInfo = new KeyInfo();
            KeyInfoX509Data keyData = new KeyInfoX509Data(cert2);

            keyInfo.AddClause(keyData);

            sig.KeyInfo = keyInfo;

            // Compute the signature.
            sig.ComputeSignature();

            // Get the XML representation of the signature and save it to an XmlElement object.
            XmlElement xmlDigitalSignature = sig.GetXml();

            return xmlDigitalSignature;
        }
Example #16
0
 private static byte[] CalculateC14nByteRange(XmlDocument doc) {
     XmlDsigC14NTransform c14nTransform = new XmlDsigC14NTransform();
     c14nTransform.LoadInput(doc);
     return ((MemoryStream)c14nTransform.GetOutput()).ToArray();
 }
Example #17
0
 private static byte[] CalculateC14nByteRange(XmlElement element, XmlDocument doc) {
     XmlElement cloneElement = (XmlElement)element.CloneNode(true);
     NormalizeNamespaces(element.CreateNavigator(), cloneElement.CreateNavigator());
     XmlDocument elememntDoc = new XmlDocument(doc.NameTable);
     elememntDoc.LoadXml(cloneElement.OuterXml);
     XmlDsigC14NTransform c14nTransform = new XmlDsigC14NTransform();
     c14nTransform.LoadInput(elememntDoc);
     return ((MemoryStream)c14nTransform.GetOutput()).ToArray();
 }
Example #18
0
        public void LoadXml(XmlElement value)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            if ((value.LocalName != XmlSignature.ElementNames.Reference) || (value.NamespaceURI != XmlSignature.NamespaceURI))
            {
                throw new CryptographicException();
            }

            id   = GetAttribute(value, XmlSignature.AttributeNames.Id);
            uri  = GetAttribute(value, XmlSignature.AttributeNames.URI);
            type = GetAttribute(value, XmlSignature.AttributeNames.Type);
            // Note: order is important for validations
            XmlNodeList xnl = value.GetElementsByTagName(XmlSignature.ElementNames.Transform, XmlSignature.NamespaceURI);

            if ((xnl != null) && (xnl.Count > 0))
            {
                Transform t = null;
                foreach (XmlNode xn in xnl)
                {
                    string a = GetAttribute((XmlElement)xn, XmlSignature.AttributeNames.Algorithm);

/*	This code is useful for debugging in VS.NET because using CryptoConfig
 *      (from MS mscorlib) would throw InvalidCastException because it's
 *      Transform would come from MS System.Security.dll not Mono's.*/
                    switch (a)
                    {
                    case "http://www.w3.org/2000/09/xmldsig#base64":
                        t = new XmlDsigBase64Transform();
                        break;

                    case "http://www.w3.org/TR/2001/REC-xml-c14n-20010315":
                        t = new XmlDsigC14NTransform();
                        break;

                    case "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments":
                        t = new XmlDsigC14NWithCommentsTransform();
                        break;

                    case "http://www.w3.org/2000/09/xmldsig#enveloped-signature":
                        t = new XmlDsigEnvelopedSignatureTransform();
                        break;

                    case "http://www.w3.org/TR/1999/REC-xpath-19991116":
                        t = new XmlDsigXPathTransform();
                        break;

                    case "http://www.w3.org/TR/1999/REC-xslt-19991116":
                        t = new XmlDsigXsltTransform();
                        break;

                    case "http://www.w3.org/2002/07/decrypt#XML":
                        t = new XmlDecryptionTransform();
                        break;

                    case "http://www.w3.org/2001/10/xml-exc-c14n#":
                        t = new XmlDsigExcC14NTransform();
                        break;

                    default:
                        throw new NotSupportedException();
                    }

                    if (t == null)
                    {
                        t = (Transform)CryptoConfig.CreateFromName(a);
                    }
                    if (t == null)
                    {
                        throw new CryptographicException("Unknown transform {0}.", a);
                    }

                    if (xn.ChildNodes.Count > 0)
                    {
                        t.LoadInnerXml(xn.ChildNodes);
                    }
                    AddTransform(t);
                }
            }
            // get DigestMethod
            DigestMethod = XmlSignature.GetAttributeFromElement(value, XmlSignature.AttributeNames.Algorithm, XmlSignature.ElementNames.DigestMethod);
            // get DigestValue
            XmlElement dig = XmlSignature.GetChildElement(value, XmlSignature.ElementNames.DigestValue, XmlSignature.NamespaceURI);

            if (dig != null)
            {
                DigestValue = Convert.FromBase64String(dig.InnerText);
            }
            element = value;
        }
Example #19
0
		public void PrefixlessNamespaceOutput ()
		{
			XmlDocument doc = new XmlDocument ();
			doc.AppendChild (doc.CreateElement ("foo", "urn:foo"));
			doc.DocumentElement.AppendChild (doc.CreateElement ("bar", "urn:bar"));
			Assert.AreEqual (String.Empty, doc.DocumentElement.GetAttribute ("xmlns"), "#1");
			XmlDsigC14NTransform t = new XmlDsigC14NTransform ();
			t.LoadInput (doc);
			Stream s = t.GetOutput () as Stream;
			Assert.AreEqual (new StreamReader (s, Encoding.UTF8).ReadToEnd (), "<foo xmlns=\"urn:foo\"><bar xmlns=\"urn:bar\"></bar></foo>");
			Assert.AreEqual ("urn:foo", doc.DocumentElement.GetAttribute ("xmlns"), "#2");
		}
Example #20
0
		public void SimpleNamespacePrefixes ()
		{
			string input = "<a:Action xmlns:a='urn:foo'>http://tempuri.org/IFoo/Echo</a:Action>";
			string expected = @"<a:Action xmlns:a=""urn:foo"">http://tempuri.org/IFoo/Echo</a:Action>";

			XmlDocument doc = new XmlDocument ();
			doc.LoadXml (input);
			XmlDsigC14NTransform t = new XmlDsigC14NTransform ();
			t.LoadInput (doc);
			Stream s = t.GetOutput () as Stream;
			Assert.AreEqual (new StreamReader (s, Encoding.UTF8).ReadToEnd (), expected);
		}
Example #21
0
		public XmlDocument SaveWithSignature(AsymmetricAlgorithm key)
		{
			XmlDocument doc = Save();
	
			SignedXml sign = new SignedXml(doc);

			Reference reference = new Reference();
			reference.Uri = "";

			Transform trns = new XmlDsigC14NTransform();
			reference.AddTransform(trns);

			XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
			reference.AddTransform(env);

			sign.AddReference(reference);

			sign.SigningKey = key;
            sign.Resolver = null;

			sign.ComputeSignature();

			XmlElement xmlDigitalSignature = sign.GetXml();

			doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));
                
			return doc;
		}
Example #22
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 #23
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 #24
0
 public void SignXmlText(string XMLFile, string SignedXMLFileName, string PrivateKeyPassword, string CertificateFileName)
 {
     XmlDocument doc = new XmlDocument();
     doc.PreserveWhitespace = false;
     doc.LoadXml(XMLFile);
     SignedXml signedXml = new SignedXml(doc);
     AsymmetricCipherKeyPair kp = this.readKey1(CertificateFileName, PrivateKeyPassword);
     AsymmetricKeyParameter privateKey = kp.Private;
     System.Security.Cryptography.RSA Key = DotNetUtilities.ToRSA((RsaPrivateCrtKeyParameters)privateKey);
     signedXml.SigningKey = Key;
     Reference reference = new Reference();
     reference.Uri = "";
     XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
     reference.AddTransform(env);
     XmlDsigC14NTransform c14t = new XmlDsigC14NTransform();
     reference.AddTransform(c14t);
     signedXml.AddReference(reference);
     KeyInfo keyInfo = new KeyInfo();
     System.Security.Cryptography.X509Certificates.X509Certificate MSCert = System.Security.Cryptography.X509Certificates.X509Certificate.CreateFromCertFile(CertificateFileName);
     keyInfo.AddClause(new KeyInfoX509Data(MSCert));
     signedXml.KeyInfo = keyInfo;
     signedXml.ComputeSignature();
     XmlElement xmlDigitalSignature = signedXml.GetXml();
     doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));
     if (doc.FirstChild is XmlDeclaration)
     {
         doc.RemoveChild(doc.FirstChild);
     }
     XmlTextWriter xmltw = new XmlTextWriter(SignedXMLFileName, new System.Text.UTF8Encoding(false));
     doc.WriteTo(xmltw);
     xmltw.Close();
 }
Example #25
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 #26
0
        public virtual void LoadXml(XmlElement value)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }
            else
            {
                Uri            = null;
                TransformChain = new TransformChain();

                foreach (XmlNode n in value.ChildNodes)
                {
                    if (n is XmlWhitespace)
                    {
                        continue;
                    }

                    switch (n.LocalName)
                    {
                    case XmlEncryption.ElementNames.Transforms:
                        foreach (XmlNode xn in ((XmlElement)n).GetElementsByTagName(XmlSignature.ElementNames.Transform, XmlSignature.NamespaceURI))
                        {
                            Transform t = null;
                            switch (((XmlElement)xn).Attributes [XmlSignature.AttributeNames.Algorithm].Value)
                            {
                            case XmlSignature.AlgorithmNamespaces.XmlDsigBase64Transform:
                                t = new XmlDsigBase64Transform();
                                break;

                            case XmlSignature.AlgorithmNamespaces.XmlDsigC14NTransform:
                                t = new XmlDsigC14NTransform();
                                break;

                            case XmlSignature.AlgorithmNamespaces.XmlDsigC14NWithCommentsTransform:
                                t = new XmlDsigC14NWithCommentsTransform();
                                break;

                            case XmlSignature.AlgorithmNamespaces.XmlDsigEnvelopedSignatureTransform:
                                t = new XmlDsigEnvelopedSignatureTransform();
                                break;

                            case XmlSignature.AlgorithmNamespaces.XmlDsigXPathTransform:
                                t = new XmlDsigXPathTransform();
                                break;

                            case XmlSignature.AlgorithmNamespaces.XmlDsigXsltTransform:
                                t = new XmlDsigXsltTransform();
                                break;

#if NET_2_0
                            case XmlSignature.AlgorithmNamespaces.XmlDsigExcC14NTransform:
                                t = new XmlDsigExcC14NTransform();
                                break;

                            case XmlSignature.AlgorithmNamespaces.XmlDsigExcC14NWithCommentsTransform:
                                t = new XmlDsigExcC14NWithCommentsTransform();
                                break;

                            case XmlSignature.AlgorithmNamespaces.XmlDecryptionTransform:
                                t = new XmlDecryptionTransform();
                                break;
#endif
                            default:
                                continue;
                            }

                            t.LoadInnerXml(((XmlElement)xn).ChildNodes);
                            TransformChain.Add(t);
                        }
                        break;
                    }
                }

                if (value.HasAttribute(XmlEncryption.AttributeNames.URI))
                {
                    Uri = value.Attributes [XmlEncryption.AttributeNames.URI].Value;
                }
            }
        }
Example #27
0
		public void SignElementWithoutPrefixedNamespace ()
		{
			string input = "<Action xmlns='urn:foo'>http://tempuri.org/IFoo/Echo</Action>";
			string expected = @"<Signature xmlns=""http://www.w3.org/2000/09/xmldsig#""><SignedInfo><CanonicalizationMethod Algorithm=""http://www.w3.org/TR/2001/REC-xml-c14n-20010315"" /><SignatureMethod Algorithm=""http://www.w3.org/2000/09/xmldsig#hmac-sha1"" /><Reference URI=""#_1""><Transforms><Transform Algorithm=""http://www.w3.org/TR/2001/REC-xml-c14n-20010315"" /></Transforms><DigestMethod Algorithm=""http://www.w3.org/2000/09/xmldsig#sha1"" /><DigestValue>zdFEZB8rNzvpNG/gFEJBWk/M5Nk=</DigestValue></Reference></SignedInfo><SignatureValue>+OyGVzrHjmKSDWLNyvgx8pjbPfM=</SignatureValue><Object Id=""_1""><Action xmlns=""urn:foo"">http://tempuri.org/IFoo/Echo</Action></Object></Signature>";

			byte [] key = Convert.FromBase64String (
				"1W5EigVnbnRjGLbg99ElieOmuUgYO+KcwMJtE35SAGI=");
			Transform t = new XmlDsigC14NTransform ();
			Assert.AreEqual (expected, SignWithHMACSHA1 (input, key, t), "#1");
			// The second result should be still identical.
			Assert.AreEqual (expected, SignWithHMACSHA1 (input, key, t), "#2");
		}
Example #28
0
        public static SignatureType GeraAssinatura(XmlDocument doc, string pUri, X509Certificate2 cert)
        {
            try
            {
                var signature = doc.GetElementsByTagName("Signature");
                if (signature.Count == 1)
                {
                    signature.Item(0).ParentNode.RemoveChild(signature.Item(0));
                }
                else if (signature.Count > 1)
                {
                    throw new InvalidOperationException("Não é possível assinar um documento com mais de uma assinatura existente.");
                }

                // Create a SignedXml object.
                var signedXml = new SignedXml(doc) {SigningKey = cert.PrivateKey};

                // Create a reference to be signed.
                var reference = new Reference();
                // pega o uri que deve ser assinada
                var uri = doc.GetElementsByTagName(pUri).Item(0).Attributes;
                foreach (XmlAttribute atributo in uri) {
                    if (atributo.Name == "Id") {
                        reference.Uri = "#" + atributo.InnerText;
                    }
                }

                // Add an enveloped transformation to the reference.
                var env = new XmlDsigEnvelopedSignatureTransform();
                reference.AddTransform(env);

                var c14 = new XmlDsigC14NTransform();
                reference.AddTransform(c14);

                // Add the reference to the SignedXml object.
                signedXml.AddReference(reference);

                // Create a new KeyInfo object.
                var keyInfo = new KeyInfo();

                // Load the certificate into a KeyInfoX509Data object
                // and add it to the KeyInfo object.
                keyInfo.AddClause(new KeyInfoX509Data(cert));

                // Add the KeyInfo object to the SignedXml object.
                signedXml.KeyInfo = keyInfo;

                // Compute the signature.
                signedXml.ComputeSignature();

                var xml = signedXml.GetXml();

                using (var sw = new StringWriter())
                using (var xw = new XmlTextWriter(sw))
                {
                    xml.WriteTo(xw);
                    xw.Close();

                    var sigXml = sw.ToString();
                    return SignatureType.Deserialize(sigXml);
                }
            } catch (Exception ex) {
                throw new Exception("Erro ao efetuar assinatura digital, detalhes: " + ex.Message);
            }
        }
Example #29
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 #30
0
		public void DataReferenceToNonDataObject ()
		{
			XmlDocument doc = new XmlDocument ();
			doc.LoadXml ("<foo Id='id:1'/>");
			SignedXml signedXml = new SignedXml (doc);
			DSA key = DSA.Create ();
			signedXml.SigningKey = key;

			Reference reference = new Reference ();
			reference.Uri = "#id:1";

			XmlDsigC14NTransform t = new XmlDsigC14NTransform ();
			reference.AddTransform (t);
			signedXml.AddReference (reference);

			signedXml.ComputeSignature ();
		}
		public override void LoadXml (XmlElement value)
		{
			if (value == null)
				throw new ArgumentNullException ("value");
			if ((value.LocalName != XmlEncryption.ElementNames.CipherReference) || (value.NamespaceURI != EncryptedXml.XmlEncNamespaceUrl))
				throw new CryptographicException ("Malformed CipherReference element.");
			else {
				Uri = null;
				TransformChain = new TransformChain ();

				foreach (XmlNode n in value.ChildNodes) {
					if (n is XmlWhitespace)
						continue;

					switch (n.LocalName) {
					case XmlEncryption.ElementNames.Transforms:
						foreach (XmlNode xn in ((XmlElement) n).GetElementsByTagName (XmlSignature.ElementNames.Transform, XmlSignature.NamespaceURI)) {
							Transform t = null;
							switch (((XmlElement) xn).Attributes [XmlSignature.AttributeNames.Algorithm].Value) {
							case XmlSignature.AlgorithmNamespaces.XmlDsigBase64Transform:
								t = new XmlDsigBase64Transform ();
								break;
							case XmlSignature.AlgorithmNamespaces.XmlDsigC14NTransform:
								t = new XmlDsigC14NTransform ();
								break;
							case XmlSignature.AlgorithmNamespaces.XmlDsigC14NWithCommentsTransform:
								t = new XmlDsigC14NWithCommentsTransform ();
								break;
							case XmlSignature.AlgorithmNamespaces.XmlDsigEnvelopedSignatureTransform:
								t = new XmlDsigEnvelopedSignatureTransform ();
								break;
							case XmlSignature.AlgorithmNamespaces.XmlDsigXPathTransform:
								t = new XmlDsigXPathTransform ();
								break;
							case XmlSignature.AlgorithmNamespaces.XmlDsigXsltTransform:
								t = new XmlDsigXsltTransform ();
								break;
#if NET_2_0
							case XmlSignature.AlgorithmNamespaces.XmlDecryptionTransform:
								t = new XmlDecryptionTransform ();
								break;
#endif
							default:
								continue;
							}

							t.LoadInnerXml (((XmlElement) xn).ChildNodes);
							TransformChain.Add (t);
						}
						break;
					}
				}
						
				if (value.HasAttribute (XmlEncryption.AttributeNames.URI))
					Uri = value.Attributes [XmlEncryption.AttributeNames.URI].Value;
			}
		}
Example #32
0
        /// <summary>
        /// Gera assinatura Digital do XML
        /// </summary>
        /// <param name="XMLString"></param>
        /// <param name="RefUri"></param>
        /// <param name="X509Cert"></param>
        /// <returns></returns>
        public int Assinar(string XMLString, string RefUri, X509Certificate2 X509Cert)
        {


            int resultado = 0;
            msgResultado = "Assinatura realizada com sucesso";
            try
            {
                //   certificado para ser utilizado na assinatura
                //
                string _xnome = "";

                bool bX509Cert = false;

                if (X509Cert != null)
                {
                    _xnome = X509Cert.Subject.ToString();
                }
                else
                {
                    bX509Cert = true;
                }
                X509Certificate2 _X509Cert = new X509Certificate2();
                X509Store store = new X509Store("MY", StoreLocation.CurrentUser);
                store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
                X509Certificate2Collection collection = (X509Certificate2Collection)store.Certificates;
                X509Certificate2Collection collection1 = (X509Certificate2Collection)collection.Find(X509FindType.FindBySubjectDistinguishedName, (object)_xnome, true);

                //if (collection1.Count == 0)
                if (bX509Cert)
                {
                    resultado = 2;
                    msgResultado = "Problemas no certificado digital";
                }
                else
                {
                    // certificado ok
                    //_X509Cert = collection1[0];

                    _X509Cert = X509Cert;
                    string x;
                    x = _X509Cert.GetKeyAlgorithm().ToString();
                    // Create a new XML document.

                    XmlDocument doc = new XmlDocument();

                    // Format the document to ignore white spaces.
                    doc.PreserveWhitespace = false;

                    // Load the passed XML file using it's name.
                    try
                    {
                        doc.LoadXml(XMLString);

                        // Verifica se a tag a ser assinada existe é única
                        int qtdeRefUri = doc.GetElementsByTagName(RefUri).Count;

                        if (qtdeRefUri == 0)
                        {
                            //  a URI indicada não existe
                            resultado = 4;
                            msgResultado = "A tag de assinatura " + RefUri.Trim() + " inexiste";
                        }
                        // Exsiste mais de uma tag a ser assinada
                        else
                        {

                            if (qtdeRefUri > 1)
                            {
                                // existe mais de uma URI indicada
                                resultado = 5;
                                msgResultado = "A tag de assinatura " + RefUri.Trim() + " não é unica";

                            }
                            else
                            {
                                try
                                {
                                    //Claudinei - o.s. 23615 - 10/08/2009
                                    //for (int i = 0; i < qtdeRefUri; i++)
                                    {
                                        //Fim - Claudinei - o.s. 23615 - 10/08/2009

                                        // Create a SignedXml object.
                                        SignedXml signedXml = new SignedXml(doc);

                                        //sTipoAssinatura = _X509Cert.PrivateKey.KeySize.ToString();
                                        // Add the key to the SignedXml document 
                                        signedXml.SigningKey = _X509Cert.PrivateKey;

                                        // Create a reference to be signed
                                        Reference reference = new Reference();
                                        // pega o uri que deve ser assinada
                                        XmlAttributeCollection _Uri = doc.GetElementsByTagName(RefUri).Item(0).Attributes; //Claudinei - o.s. 23615 - 10/08/2009
                                        foreach (XmlAttribute _atributo in _Uri)
                                        {
                                            if (_atributo.Name == "Id")
                                            {
                                                reference.Uri = "#" + _atributo.InnerText;
                                            }
                                        }

                                        // Add an enveloped transformation to the reference.
                                        XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
                                        reference.AddTransform(env);

                                        XmlDsigC14NTransform c14 = new XmlDsigC14NTransform();
                                        reference.AddTransform(c14);

                                        // Add the reference to the SignedXml object.
                                        signedXml.AddReference(reference);

                                        // Create a new KeyInfo object
                                        KeyInfo keyInfo = new KeyInfo();

                                        // Load the certificate into a KeyInfoX509Data object
                                        // and add it to the KeyInfo object.
                                        keyInfo.AddClause(new KeyInfoX509Data(_X509Cert));

                                        // Add the KeyInfo object to the SignedXml object.
                                        signedXml.KeyInfo = keyInfo;

                                        signedXml.ComputeSignature();

                                        // Get the XML representation of the signature and save
                                        // it to an XmlElement object.
                                        XmlElement xmlDigitalSignature = signedXml.GetXml();

                                        // Append the element to the XML document.

                                        //Claudinei - o.s. 23581 - 07/07/2009
                                        /*
                                        string teste = "";
                                        //XmlNode xmlno = new XmlNode();
                                        foreach (XmlNode xmlno in doc)
                                        {
                                            teste = xmlno.Name.ToString();
                                        }
                                         */
                                        //Fim - Claudinei - o.s. 23581 - 07/07/2009

                                        //Danner - o.s. 23732 - 11/11/2009
                                        doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));
                                        //Fim - Danner - o.s. 23732 - 11/11/2009
                                        XMLDoc = new XmlDocument();
                                        XMLDoc.PreserveWhitespace = false;
                                        XMLDoc = doc;
                                    } //Claudinei - o.s. 23615 - 10/08/2009
                                }

                                catch (Exception caught)
                                {
                                    resultado = 7;
                                    msgResultado = "Erro: Ao assinar o documento - " + caught.Message;
                                }

                            }
                        }
                    }

                    catch (Exception caught)
                    {
                        resultado = 3;
                        msgResultado = "Erro: XML mal formado - " + caught.Message;
                    }
                }
            }
            catch (Exception caught)
            {
                resultado = 1;
                msgResultado = "Erro: Problema ao acessar o certificado digital" + caught.Message;
            }

            return resultado;
        }
        private String Assinar(Nota nota, X509Certificate2 x509Cert, String TagAssinatura, String URI = "")
        {
            string xmlString;
            using (var srReader = File.OpenText(nota.CaminhoFisico))
            {
                xmlString = srReader.ReadToEnd();
            }

            // Create a new XML document.
            var doc = new XmlDocument();

            // Format the document to ignore white spaces.
            doc.PreserveWhitespace = false;
            doc.LoadXml(xmlString);

            XmlDocument xMLDoc;

            var reference = new Reference();
            if (!String.IsNullOrEmpty(nota.NotaId))
                reference.Uri = "#" + TagAssinatura + nota.NotaId;
            else if (!String.IsNullOrEmpty(URI))
                reference.Uri = URI;

            // Create a SignedXml object.
            var signedXml = new SignedXml(doc);

            // Add the key to the SignedXml document
            signedXml.SigningKey = x509Cert.PrivateKey;

            // Add an enveloped transformation to the reference.
            var env = new XmlDsigEnvelopedSignatureTransform();
            reference.AddTransform(env);

            var c14 = new XmlDsigC14NTransform();
            reference.AddTransform(c14);

            // Add the reference to the SignedXml object.
            signedXml.AddReference(reference);

            // Create a new KeyInfo object
            var keyInfo = new KeyInfo();

            // Load the certificate into a KeyInfoX509Data object
            // and add it to the KeyInfo object.
            keyInfo.AddClause(new KeyInfoX509Data(x509Cert));

            // Add the KeyInfo object to the SignedXml object.
            signedXml.KeyInfo = keyInfo;
            signedXml.ComputeSignature();

            // Get the XML representation of the signature and save
            // it to an XmlElement object.
            var xmlDigitalSignature = signedXml.GetXml();

            // Gravar o elemento no documento XML
            var assinaturaNodes = doc.GetElementsByTagName(TagAssinatura);
            foreach (XmlNode nodes in assinaturaNodes)
            {
                nodes.AppendChild(doc.ImportNode(xmlDigitalSignature, true));
                break;
            }

            xMLDoc = new XmlDocument();
            xMLDoc.PreserveWhitespace = false;
            xMLDoc = doc;

            // Atualizar a string do XML já assinada
            var StringXMLAssinado = xMLDoc.OuterXml;

            //Atualiza a nota assinada
            nota.ConteudoXml = StringXMLAssinado;

            // Gravar o XML Assinado no HD
            var SignedFile = nota.CaminhoFisico;
            var SW_2 = File.CreateText(SignedFile);
            SW_2.Write(StringXMLAssinado);
            SW_2.Close();

            return SignedFile;
        }