Пример #1
0
        public static Transform fromURI(string uri)
        {
            Transform t = null;

            switch (uri)
            {
            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/2001/10/xml-exc-c14n#":
                t = new XmlDsigExcC14NTransform();
                break;
            }
            return(t);
        }
Пример #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;

        XmlDsigXsltTransform xmlTransform =
            new XmlDsigXsltTransform();

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

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

        if (absoluteUri != null)
        {
            Console.WriteLine(
                "\nResolved 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);
    }
Пример #3
0
    private static void TransformDoc(
        XmlDocument xmlDoc,
        XmlNodeList xsltNodeList)
    {
        try
        {
            // Construct a new XmlDsigXsltTransform.
            //<Snippet1>
            XmlDsigXsltTransform xmlTransform =
                new XmlDsigXsltTransform();
            //</Snippet1>

            // Load the Xslt tranform as a node list.
            //<Snippet10>
            xmlTransform.LoadInnerXml(xsltNodeList);
            //</Snippet10>

            // Load the Xml document to perform the tranform on.
            //<Snippet11>
            XmlNamespaceManager namespaceManager;
            namespaceManager = new XmlNamespaceManager(xmlDoc.NameTable);

            XmlNodeList productsNodeList;
            productsNodeList = xmlDoc.SelectNodes("//.", namespaceManager);

            xmlTransform.LoadInput(productsNodeList);
            //</Snippet11>

            // Retrieve the output from the transform.
            //<Snippet7>
            Stream outputStream = (Stream)
                                  xmlTransform.GetOutput(typeof(System.IO.Stream));
            //</Snippet7>

            // Read the output stream 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("\nResult of transformation: " + outputMessage);
            ShowTransformProperties(xmlTransform);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Caught exception in TransformDoc method: " +
                              ex.ToString());
        }
    }
Пример #4
0
    // Create the XML that represents the transform.
    public static XmlDsigXsltTransform CreateXsltTransform(string xsl)
    {
        XmlDocument doc = new XmlDocument();

        doc.LoadXml(xsl);

        XmlDsigXsltTransform xform = new XmlDsigXsltTransform();

        xform.LoadInnerXml(doc.ChildNodes);

        return(xform);
    }
        public void DecryptData_CipherReference_IdUri()
        {
            XmlDocument doc = new XmlDocument();

            doc.PreserveWhitespace = true;
            string xml = "<root>  <child>sample</child>   </root>";

            doc.LoadXml(xml);

            var random  = new SecureRandom();
            var ivdata  = new byte[128 / 8];
            var keydata = new byte[256 / 8];

            random.NextBytes(ivdata);
            random.NextBytes(keydata);
            var param = new ParametersWithIV(new KeyParameter(keydata), ivdata);

            XmlEncryption exml        = new XmlEncryption(doc);
            XmlDecryption dexml       = new XmlDecryption(doc);
            string        cipherValue = Convert.ToBase64String(exml.EncryptData(Encoding.UTF8.GetBytes(xml), param));

            EncryptedData ed = new EncryptedData();

            ed.Type             = XmlNameSpace.Url[NS.XmlEncElementUrl];
            ed.EncryptionMethod = new EncryptionMethod(NS.XmlEncAES256Url);
            ed.CipherData       = new CipherData();

            ed.CipherData.CipherReference = new CipherReference("#ID_0");
            string xslt = "<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"><xsl:template match = \"/\"><xsl:value-of select=\".\" /></xsl:template></xsl:stylesheet>";
            XmlDsigXsltTransform xsltTransform = new XmlDsigXsltTransform();
            XmlDocument          xsltDoc       = new XmlDocument();

            xsltDoc.LoadXml(xslt);
            xsltTransform.LoadInnerXml(xsltDoc.ChildNodes);
            ed.CipherData.CipherReference.AddTransform(xsltTransform);
            ed.CipherData.CipherReference.AddTransform(new XmlDsigBase64Transform());


            doc.LoadXml("<root></root>");
            XmlNode encryptedDataNode = doc.ImportNode(ed.GetXml(), true);

            doc.DocumentElement.AppendChild(encryptedDataNode);
            XmlElement cipherDataByReference = doc.CreateElement("CipherData");

            cipherDataByReference.SetAttribute("ID", "ID_0");
            cipherDataByReference.InnerText = cipherValue;
            doc.DocumentElement.AppendChild(cipherDataByReference);

            string decryptedXmlString = Encoding.UTF8.GetString(dexml.DecryptData(ed, param));

            Assert.Equal(xml, decryptedXmlString);
        }
Пример #6
0
    // Encrypt the text in the specified XmlDocument.
    private static void ShowTransformProperties(
        XmlDsigXsltTransform xmlTransform)
    {
        //<Snippet12>
        string classDescription = xmlTransform.ToString();

        //</Snippet12>
        Console.WriteLine("\n** Summary for " + classDescription + " **");

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

        //</Snippet9>
        Console.WriteLine("Xml representation of the current transform:\n" +
                          xmlInTransform.OuterXml);

        // Ensure the transform is using the proper algorithm.
        //<Snippet3>
        xmlTransform.Algorithm =
            SignedXml.XmlDsigXsltTransformUrl;
        //</Snippet3>
        Console.WriteLine("Algorithm used: " + classDescription);

        // Retrieve the valid input types for the current transform.
        //<Snippet4>
        Type[] validInTypes = xmlTransform.InputTypes;
        //</Snippet4>
        Console.WriteLine("Transform accepts the following inputs:");
        for (int i = 0; i < validInTypes.Length; i++)
        {
            Console.WriteLine("\t" + validInTypes[i].ToString());
        }

        //<Snippet5>
        Type[] validOutTypes = xmlTransform.OutputTypes;
        //</Snippet5>
        Console.WriteLine("Transform outputs in the following types:");
        for (int i = validOutTypes.Length - 1; i >= 0; i--)
        {
            Console.WriteLine("\t " + validOutTypes[i].ToString());

            if (validOutTypes[i] == typeof(object))
            {
                //<Snippet8>
                object outputObject = xmlTransform.GetOutput();
                //</Snippet8>
            }
        }
    }
Пример #7
0
        void CheckProperties(XmlDsigXsltTransform transform)
        {
            Assert.Equal("http://www.w3.org/TR/1999/REC-xslt-19991116", transform.Algorithm);

            Type[] input = transform.InputTypes;
            Assert.True((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.True(istream, "Input Stream");
            Assert.True(ixmldoc, "Input XmlDocument");
            Assert.True(ixmlnl, "Input XmlNodeList");

            Type[] output = transform.OutputTypes;
            Assert.True((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.True(ostream, "Output Stream");
        }
Пример #8
0
        public void DecryptData_CipherReference_IdUri()
        {
            XmlDocument doc = new XmlDocument();

            doc.PreserveWhitespace = true;
            string xml = "<root>  <child>sample</child>   </root>";

            doc.LoadXml(xml);

            using (Aes aes = Aes.Create())
            {
                EncryptedXml exml        = new EncryptedXml(doc);
                string       cipherValue = Convert.ToBase64String(exml.EncryptData(Encoding.UTF8.GetBytes(xml), aes));

                EncryptedData ed = new EncryptedData();
                ed.Type             = EncryptedXml.XmlEncElementUrl;
                ed.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url);
                ed.CipherData       = new CipherData();
                // Create CipherReference: first extract node value, then convert from base64 using Transforms
                ed.CipherData.CipherReference = new CipherReference("#ID_0");
                string xslt = "<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"><xsl:template match = \"/\"><xsl:value-of select=\".\" /></xsl:template></xsl:stylesheet>";
                XmlDsigXsltTransform xsltTransform = new XmlDsigXsltTransform();
                XmlDocument          xsltDoc       = new XmlDocument();
                xsltDoc.LoadXml(xslt);
                xsltTransform.LoadInnerXml(xsltDoc.ChildNodes);
                ed.CipherData.CipherReference.AddTransform(xsltTransform);
                ed.CipherData.CipherReference.AddTransform(new XmlDsigBase64Transform());

                // Create a document with EncryptedData and node with the actual cipher data (with the ID)
                doc.LoadXml("<root></root>");
                XmlNode encryptedDataNode = doc.ImportNode(ed.GetXml(), true);
                doc.DocumentElement.AppendChild(encryptedDataNode);
                XmlElement cipherDataByReference = doc.CreateElement("CipherData");
                cipherDataByReference.SetAttribute("ID", "ID_0");
                cipherDataByReference.InnerText = cipherValue;
                doc.DocumentElement.AppendChild(cipherDataByReference);

                if (PlatformDetection.IsXmlDsigXsltTransformSupported)
                {
                    string decryptedXmlString = Encoding.UTF8.GetString(exml.DecryptData(ed, aes));
                    Assert.Equal(xml, decryptedXmlString);
                }
            }
        }
Пример #9
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);
        }
        private static XmlDsigXsltTransform CreateDataTransform()
        {
            var dataTransformDocument = new XmlDocument();

            dataTransformDocument.LoadXml(@"
				<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform' xmlns:ds='http://www.w3.org/2000/09/xmldsig#'>
					<xsl:template match='/'>
						<xsl:apply-templates />
					</xsl:template>
					<xsl:template match='*'>
						<xsl:copy>
							<xsl:copy-of select='@*' />
							<xsl:apply-templates />
						</xsl:copy>
					</xsl:template>
					<xsl:template match='ds:Signature' />
				</xsl:stylesheet>"                );

            var dataTransform = new XmlDsigXsltTransform();

            dataTransform.LoadInnerXml(dataTransformDocument.ChildNodes);

            return(dataTransform);
        }
Пример #11
0
    // Sign an XML file and save the signature in a new file.
    public static void SignXmlFile(string FileName, string SignedFileName, RSA Key, string XSLString)
    {
        // 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.
        doc.Load(new XmlTextReader(FileName));

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

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

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

        reference.Uri = "";

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

        reference.AddTransform(env);

        // Create an XmlDsigXPathTransform object using
        // the helper method 'CreateXPathTransform' defined
        // later in this sample.

        XmlDsigXsltTransform XsltTransform = CreateXsltTransform(XSLString);

        // Add the transform to the reference.
        reference.AddTransform(XsltTransform);

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

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

        keyInfo.AddClause(new RSAKeyValue((RSA)Key));
        signedXml.KeyInfo = keyInfo;

        // Compute the signature.
        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.
        doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));

        // Save the signed XML document to a file specified
        // using the passed string.
        XmlTextWriter xmltw = new XmlTextWriter(SignedFileName, new UTF8Encoding(false));

        doc.WriteTo(xmltw);
        xmltw.Close();
    }