Пример #1
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);
        }
Пример #2
0
    // Resolve the specified base and relative Uri's .
    private static Uri ResolveUris(Uri baseUri, string relativeUri)
    {
        //<Snippet6>
        XmlUrlResolver xmlResolver = new XmlUrlResolver();

        xmlResolver.Credentials =
            System.Net.CredentialCache.DefaultCredentials;

        XmlDsigBase64Transform xmlTransform = new XmlDsigBase64Transform();

        xmlTransform.Resolver = xmlResolver;
        //</Snippet6>

        Uri absoluteUri = xmlResolver.ResolveUri(baseUri, relativeUri);

        if (absoluteUri != null)
        {
            Console.WriteLine(
                "Resolved the base Uri and relative Uri to the following:");
            Console.WriteLine(absoluteUri.ToString());
        }
        else
        {
            Console.WriteLine(
                "Unable to resolve the base Uri and relative Uri");
        }
        return(absoluteUri);
    }
        /// <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>
        private void SetContentInternallyDetached(SignatureDocument sigDocument, XmlDocument xmlDocument, string elementId, string mimeType)
        {
            sigDocument.Document = xmlDocument;

            _refContent = new Reference();

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

            _mimeType = mimeType;

            if (mimeType == "text/xml")
            {
                XmlDsigC14NTransform transform = new XmlDsigC14NTransform();
                _refContent.AddTransform(transform);

                _encoding = "UTF-8";
            }
            else
            {
                XmlDsigBase64Transform transform = new XmlDsigBase64Transform();
                _refContent.AddTransform(transform);

                _encoding = transform.Algorithm;
            }

            sigDocument.XadesSignature = new XadesSignedXml(sigDocument.Document);

            sigDocument.XadesSignature.AddReference(_refContent);
        }
Пример #4
0
        private void SetContentInternallyDetached(SignatureDocument sigDocument, Stream input, string mimeType)
        {
            sigDocument.Document = new XmlDocument();
            XmlElement xmlElement = sigDocument.Document.CreateElement("DOCFIRMA");

            sigDocument.Document.AppendChild(xmlElement);
            Guid   guid = Guid.NewGuid();
            string text = "CONTENT-" + guid.ToString();

            _refContent     = new Reference();
            _refContent.Uri = "#" + text;
            Reference refContent = _refContent;

            guid             = Guid.NewGuid();
            refContent.Id    = "Reference-" + guid.ToString();
            _refContent.Type = "http://www.w3.org/2000/09/xmldsig#Object";
            _mimeType        = mimeType;
            XmlElement xmlElement2 = sigDocument.Document.CreateElement("CONTENT");

            if (mimeType == "text/xml")
            {
                _encoding = "UTF-8";
                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.PreserveWhitespace = true;
                xmlDocument.Load(input);
                xmlElement2.InnerXml = xmlDocument.DocumentElement.OuterXml;
                XmlDsigC14NTransform transform = new XmlDsigC14NTransform();
                _refContent.AddTransform(transform);
            }
            else
            {
                XmlDsigBase64Transform xmlDsigBase64Transform = new XmlDsigBase64Transform();
                _refContent.AddTransform(xmlDsigBase64Transform);
                _encoding = xmlDsigBase64Transform.Algorithm;
                if (mimeType == "hash/sha256")
                {
                    using (SHA256 sHA = SHA256.Create())
                    {
                        xmlElement2.InnerText = Convert.ToBase64String(sHA.ComputeHash(input));
                    }
                }
                else
                {
                    using (MemoryStream memoryStream = new MemoryStream())
                    {
                        input.CopyTo(memoryStream);
                        xmlElement2.InnerText = Convert.ToBase64String(memoryStream.ToArray());
                    }
                }
            }
            xmlElement2.SetAttribute("Id", text);
            xmlElement2.SetAttribute("MimeType", _mimeType);
            xmlElement2.SetAttribute("Encoding", _encoding);
            xmlElement.AppendChild(xmlElement2);
            sigDocument.XadesSignature = new XadesSignedXml(sigDocument.Document);
            sigDocument.XadesSignature.AddReference(_refContent);
        }
Пример #5
0
        static void Main(string[] args)
        {
            //Create a URI string.
            String uri = "http://www.woodgrovebank.com/document.xml";
            // Create a Base64 transform. The input content retrieved from the
            // URI should be Base64-decoded before other processing.
            Transform base64 = new XmlDsigBase64Transform();
            //Create a transform chain and add the transform to it.
            TransformChain tc = new TransformChain();

            tc.Add(base64);
            //Create <CipherReference> information.
            CipherReference reference = new CipherReference(uri, tc);

            // Create a new CipherData object using the CipherReference information.
            // Note that you cannot assign both a CipherReference and a CipherValue
            // to a CipherData object.
            CipherData cd = new CipherData(reference);

            // Create a new EncryptedData object.
            EncryptedData ed = new EncryptedData();

            //Add an encryption method to the object.
            ed.Id = "ED";
            ed.EncryptionMethod = new EncryptionMethod("http://www.w3.org/2001/04/xmlenc#aes128-cbc");
            ed.CipherData       = cd;

            //Add key information to the object.
            KeyInfo ki = new KeyInfo();

            ki.AddClause(new KeyInfoRetrievalMethod("#EK", "http://www.w3.org/2001/04/xmlenc#EncryptedKey"));
            ed.KeyInfo = ki;

            // Create new XML document and put encrypted data into it.
            XmlDocument        doc = new XmlDocument();
            XmlElement         encryptionPropertyElement = (XmlElement)doc.CreateElement("EncryptionProperty", EncryptedXml.XmlEncNamespaceUrl);
            EncryptionProperty ep = new EncryptionProperty(encryptionPropertyElement);

            ed.AddProperty(ep);

            // Output the resulting XML information into a file.
            try
            {
                string path = @"c:\test\MyTest.xml";

                File.WriteAllText(path, ed.GetXml().OuterXml);
            }
            catch (IOException e)
            {
                Console.WriteLine("File IO error. {0}", e);
            }
        }
Пример #6
0
        /// <summary>
        /// Inserta un documento para generar una firma internally detached.
        /// </summary>
        /// <param name="content"></param>
        /// <param name="mimeType"></param>
        private void SetContentInternallyDetached(SignatureDocument sigDocument, Stream input)
        {
            sigDocument.Document = new XmlDocument();

            XmlElement rootElement = sigDocument.Document.CreateElement("DOCFIRMA");

            sigDocument.Document.AppendChild(rootElement);

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

            _refContent = new Reference();

            _refContent.Uri  = "#" + id;
            _refContent.Id   = "Reference-" + Guid.NewGuid().ToString();
            _refContent.Type = XadesSignedXml.XmlDsigObjectType;

            XmlElement contentElement = sigDocument.Document.CreateElement("CONTENT");

            if (_dataFormat.MimeType == "text/xml")
            {
                XmlDocument doc = new XmlDocument();
                doc.PreserveWhitespace = true;
                doc.Load(input);

                contentElement.InnerXml = doc.DocumentElement.OuterXml;

                XmlDsigC14NTransform transform = new XmlDsigC14NTransform();
                _refContent.AddTransform(transform);
            }
            else
            {
                XmlDsigBase64Transform transform = new XmlDsigBase64Transform();
                _refContent.AddTransform(transform);

                using (MemoryStream ms = new MemoryStream())
                {
                    input.CopyTo(ms);
                    contentElement.InnerText = Convert.ToBase64String(ms.ToArray(), Base64FormattingOptions.InsertLineBreaks);
                }
            }

            contentElement.SetAttribute("Id", id);
            contentElement.SetAttribute("MimeType", _dataFormat.MimeType);
            contentElement.SetAttribute("Encoding", _dataFormat.Encoding);


            rootElement.AppendChild(contentElement);

            sigDocument.XadesSignature = new XadesSignedXml(sigDocument.Document);

            sigDocument.XadesSignature.AddReference(_refContent);
        }
        public void Types()
        {
            Type [] input = transform.InputTypes;
            input [0] = null;
            input [1] = null;
            input [2] = null;
            // property does not return a clone
            foreach (Type t in transform.InputTypes)
            {
                Assert.IsNull(t);
            }
            // it's not a static array
            XmlDsigBase64Transform t2 = new XmlDsigBase64Transform();

            foreach (Type t in t2.InputTypes)
            {
                Assert.IsNotNull(t);
            }
        }
Пример #8
0
        public void Types()
        {
            Type[] input = transform.InputTypes;
            input[0] = null;
            input[1] = null;
            input[2] = null;

            foreach (Type t in transform.InputTypes)
            {
                Assert.Null(t);
            }

            XmlDsigBase64Transform t2 = new XmlDsigBase64Transform();

            foreach (Type t in t2.InputTypes)
            {
                Assert.NotNull(t);
            }
        }
        static void Main(string[] args)
        {
            //Create a URI string.
            String uri = "http://www.woodgrovebank.com/document.xml";

            // Create a Base64 transform. The input content retrieved from the
            // URI should be Base64-decoded before other processing.
            Transform base64 = new XmlDsigBase64Transform();

            //Create a transform chain and add the transform to it.
            TransformChain tc = new TransformChain();

            tc.Add(base64);

            //Create <CipherReference> information.
            CipherReference reference = new CipherReference(uri, tc);

            // Write the CipherReference value to the console.
            Console.WriteLine("Cipher Reference data: {0}", reference.GetXml().OuterXml);
        }
Пример #10
0
        public void FullChain()
        {
            TransformChain chain = new TransformChain();

            XmlDsigBase64Transform base64 = new XmlDsigBase64Transform();

            chain.Add(base64);
            Assert.Equal(base64, chain[0]);
            Assert.Equal(1, chain.Count);

            XmlDsigC14NTransform c14n = new XmlDsigC14NTransform();

            chain.Add(c14n);
            Assert.Equal(c14n, chain[1]);
            Assert.Equal(2, chain.Count);

            XmlDsigC14NWithCommentsTransform c14nc = new XmlDsigC14NWithCommentsTransform();

            chain.Add(c14nc);
            Assert.Equal(c14nc, chain[2]);
            Assert.Equal(3, chain.Count);

            XmlDsigEnvelopedSignatureTransform esign = new XmlDsigEnvelopedSignatureTransform();

            chain.Add(esign);
            Assert.Equal(esign, chain[3]);
            Assert.Equal(4, chain.Count);

            XmlDsigXPathTransform xpath = new XmlDsigXPathTransform();

            chain.Add(xpath);
            Assert.Equal(xpath, chain[4]);
            Assert.Equal(5, chain.Count);

            XmlDsigXsltTransform xslt = new XmlDsigXsltTransform();

            chain.Add(xslt);
            Assert.Equal(xslt, chain[5]);
            Assert.Equal(6, chain.Count);
        }
        /// <summary>
        /// Inserta un documento para generar una firma internally detached.
        /// </summary>
        /// <param name="content"></param>
        /// <param name="mimeType"></param>
        private void SetContentInternallyDetachedHashed(SignatureDocument sigDocument, XmlDocument input)
        {
            sigDocument.Document = new XmlDocument();

            XmlElement rootElement = sigDocument.Document.CreateElement("DOCFIRMA");

            sigDocument.Document.AppendChild(rootElement);

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

            _refContent = new Reference();

            _refContent.Uri  = "#" + id;
            _refContent.Id   = "Reference-" + Guid.NewGuid().ToString();
            _refContent.Type = XadesSignedXml.XmlDsigObjectType;

            XmlElement contentElement = sigDocument.Document.CreateElement("CONTENT");

            XmlDsigBase64Transform transform = new XmlDsigBase64Transform();

            _refContent.AddTransform(transform);

            using (SHA256 sha2 = SHA256.Create())
            {
                contentElement.InnerText = Convert.ToBase64String(sha2.ComputeHash(Encoding.UTF8.GetBytes(input.InnerXml)));
            }

            contentElement.SetAttribute("Id", id);
            contentElement.SetAttribute("MimeType", _dataFormat.MimeType);
            contentElement.SetAttribute("Encoding", _dataFormat.Encoding);

            rootElement.AppendChild(contentElement);

            sigDocument.XadesSignature = new XadesSignedXml(sigDocument.Document);

            sigDocument.XadesSignature.AddReference(_refContent);
        }
Пример #12
0
        private Transform GetCanonicalTransform()
        {
            Transform t = null;

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

            case "http://www.w3.org/2006/12/xml-c14n11#WithComments":
                t = new XmlDsigC14NTransform(true);
                break;

            case "http://www.w3.org/2000/09/xmldsig#base64":
                t = new XmlDsigBase64Transform();
                break;

            case "http://www.w3.org/TR/2002/REC-xml-exc-c14n-20020718/":
                t = new XmlDsigExcC14NTransform();
                break;
            }
            return(t);
        }
Пример #13
0
    // Encrypt the text in the specified XmlDocument.
    private static void EncryptXML(XmlDocument xmlDoc)
    {
        //<Snippet1>
        XmlDsigBase64Transform xmlTransform = new XmlDsigBase64Transform();

        //</Snippet1>

        // Ensure the transform is using the proper algorithm.
        //<Snippet3>
        xmlTransform.Algorithm = SignedXml.XmlDsigBase64TransformUrl;
        //</Snippet3>

        // Retrieve the XML representation of the current transform.
        //<Snippet9>
        XmlElement xmlInTransform = xmlTransform.GetXml();

        //</Snippet9>

        Console.WriteLine("Xml representation of the current transform: ");
        Console.WriteLine(xmlInTransform.OuterXml);

        // Retrieve the valid input types for the current transform.
        //<Snippet4>
        Type[] validInTypes = xmlTransform.InputTypes;
        //</Snippet4>

        // Verify the xmlTransform can accept the XMLDocument as an
        // input type.
        for (int i = 0; i < validInTypes.Length; i++)
        {
            if (validInTypes[i] == xmlDoc.GetType())
            {
                // Demonstrate loading the entire Xml Document.
                //<Snippet11>
                xmlTransform.LoadInput(xmlDoc);
                //</Snippet11>

                // This transform is created for demonstration purposes.
                XmlDsigBase64Transform secondTransform =
                    new XmlDsigBase64Transform();

                //<Snippet12>
                string classDescription = secondTransform.ToString();
                //</Snippet12>

                // This call does not perform as expected.
                // LoadInnerXml is overridden by the XmlDsigBase64Transform
                // class, but is stubbed out.
                //<Snippet10>
                secondTransform.LoadInnerXml(xmlDoc.SelectNodes("//."));
                //</Snippet10>

                break;
            }
        }

        //<Snippet5>
        Type[] validOutTypes = xmlTransform.OutputTypes;
        //</Snippet5>

        for (int i = 0; i < validOutTypes.Length; i++)
        {
            if (validOutTypes[i] == typeof(System.IO.Stream))
            {
                try
                {
                    //<Snippet8>
                    Type         streamType   = typeof(System.IO.Stream);
                    CryptoStream outputStream = (CryptoStream)
                                                xmlTransform.GetOutput(streamType);
                    //</Snippet8>

                    // Read the CryptoStream into a stream reader.
                    StreamReader streamReader =
                        new StreamReader(outputStream);

                    // Read the stream into a string.
                    string outputMessage = streamReader.ReadToEnd();

                    // Close the streams.
                    outputStream.Close();
                    streamReader.Close();

                    // Display to the console the Xml before and after
                    // encryption.
                    Console.WriteLine("Encoding the following message: " +
                                      xmlDoc.InnerText);
                    Console.WriteLine("Message encoded: " + outputMessage);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Unexpected exception caught: " +
                                      ex.ToString());
                }

                break;
            }
            else
            {
                //<Snippet7>
                object outputObject = xmlTransform.GetOutput();
                //</Snippet7>
            }
        }
    }
        /// <summary>
        /// Inserta un documento para generar una firma internally detached.
        /// </summary>
        /// <param name="content"></param>
        /// <param name="mimeType"></param>
        private void SetContentInternallyDetached(SignatureDocument sigDocument, Stream input, string mimeType)
        {
            sigDocument.Document = new XmlDocument();

            XmlElement rootElement = sigDocument.Document.CreateElement("DOCFIRMA");

            sigDocument.Document.AppendChild(rootElement);

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

            _refContent = new Reference();

            _refContent.Uri  = "#" + id;
            _refContent.Id   = "Reference-" + Guid.NewGuid().ToString();
            _refContent.Type = XadesSignedXml.XmlDsigObjectType;

            _mimeType = mimeType;

            XmlElement contentElement = sigDocument.Document.CreateElement("CONTENT");

            if (mimeType == "text/xml")
            {
                _encoding = "UTF-8";

                XmlDocument doc = new XmlDocument();
                doc.PreserveWhitespace = true;
                doc.Load(input);

                contentElement.InnerXml = doc.DocumentElement.OuterXml;

                XmlDsigC14NTransform transform = new XmlDsigC14NTransform();
                _refContent.AddTransform(transform);
            }
            else
            {
                XmlDsigBase64Transform transform = new XmlDsigBase64Transform();
                _refContent.AddTransform(transform);

                _encoding = transform.Algorithm;

                if (mimeType == "hash/sha256")
                {
                    using (SHA256 sha2 = SHA256.Create())
                    {
                        contentElement.InnerText = Convert.ToBase64String(sha2.ComputeHash(input));
                    }
                }
                else
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        input.CopyTo(ms);
                        contentElement.InnerText = Convert.ToBase64String(ms.ToArray());
                    }
                }
            }

            contentElement.SetAttribute("Id", id);
            contentElement.SetAttribute("MimeType", _mimeType);
            contentElement.SetAttribute("Encoding", _encoding);


            rootElement.AppendChild(contentElement);

            sigDocument.XadesSignature = new XadesSignedXml(sigDocument.Document);

            sigDocument.XadesSignature.AddReference(_refContent);
        }
Пример #15
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);
        }