• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# XmlDsigXPathTransform类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中System.Security.Cryptography.Xml.XmlDsigXPathTransform的典型用法代码示例。如果您正苦于以下问题:C# XmlDsigXPathTransform类的具体用法?C# XmlDsigXPathTransform怎么用?C# XmlDsigXPathTransform使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



XmlDsigXPathTransform类属于System.Security.Cryptography.Xml命名空间,在下文中一共展示了XmlDsigXPathTransform类的2个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: Main

//
// This example signs an XML file using an
// envelope signature. It then verifies the 
// signed XML.
//
using System;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography.Xml;
using System.Text;
using System.Xml;

public class SignVerifyEnvelope
{

    public static void Main(String[] args)
    {
        // Generate a signing key.
        RSACryptoServiceProvider Key = new RSACryptoServiceProvider();

        try
        {
            // Create an XML file to sign.
            CreateSomeXml("Example.xml");
            Console.WriteLine("New XML file created.");

            // Sign the XML that was just created and save it in a 
            // new file.
            SignXmlFile("Example.xml", "SignedExample.xml", Key, "ancestor-or-self::TempElement");
            Console.WriteLine("XML file signed.");

            // Verify the signature of the signed XML.
            Console.WriteLine("Verifying signature...");
            bool result = VerifyXmlFile("SignedExample.xml");

            // Display the results of the signature verification to \
            // the console.
            if (result)
            {
                Console.WriteLine("The XML signature is valid.");
            }
            else
            {
                Console.WriteLine("The XML signature is not valid.");
            }
        }
        catch (CryptographicException e)
        {
            Console.WriteLine(e.Message);
        }
        finally
        {
            Key.Clear();
        }
    }

    // Sign an XML file and save the signature in a new file.
    public static void SignXmlFile(string FileName, string SignedFileName, RSA Key, string XPathString)
    {
        // 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 = "";

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

        XmlDsigXPathTransform XPathTransform = CreateXPathTransform(XPathString);
        
        // Add the transform to the reference.
        reference.AddTransform(XPathTransform);

        // 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();
    }
    // Verify the signature of an XML file and return the result.
    public static Boolean VerifyXmlFile(String Name)
    {
        // Create a new XML document.
        XmlDocument xmlDocument = new XmlDocument();

        // Format using white spaces.
        xmlDocument.PreserveWhitespace = true;

        // Load the passed XML file into the document. 
        xmlDocument.Load(Name);

        // Create a new SignedXml object and pass it
        // the XML document class.
        SignedXml signedXml = new SignedXml(xmlDocument);

        // Find the "Signature" node and create a new
        // XmlNodeList object.
        XmlNodeList nodeList = xmlDocument.GetElementsByTagName("Signature");

        // Load the signature node.
        signedXml.LoadXml((XmlElement)nodeList[0]);

        // Check the signature and return the result.
        return signedXml.CheckSignature();
    }

    // Create the XML that represents the transform.
    private static XmlDsigXPathTransform CreateXPathTransform(string XPathString)
    {
        // Create a new XMLDocument object.
        XmlDocument doc = new XmlDocument();

        // Create a new XmlElement.
        XmlElement xPathElem = doc.CreateElement("XPath");

        // Set the element text to the value
        // of the XPath string.
        xPathElem.InnerText = XPathString;

        // Create a new XmlDsigXPathTransform object.
        XmlDsigXPathTransform xForm = new XmlDsigXPathTransform();

        // Load the XPath XML from the element. 
        xForm.LoadInnerXml(xPathElem.SelectNodes("."));

        // Return the XML that represents the transform.
        return xForm;
    }

    // Create example data to sign.
    public static void CreateSomeXml(string FileName)
    {
        // Create a new XmlDocument object.
        XmlDocument document = new XmlDocument();

        // Create a new XmlNode object.
        XmlNode node = document.CreateNode(XmlNodeType.Element, "", "MyXML", "Don't_Sign");

        // Append the node to the document.
        document.AppendChild(node);

        // Create a new XmlNode object.
        XmlNode subnode = document.CreateNode(XmlNodeType.Element, "", "TempElement", "Sign");

        // Add some text to the node.
        subnode.InnerText = "Here is some data to sign.";

        // Append the node to the document.
        document.DocumentElement.AppendChild(subnode);

        // Save the XML document to the file name specified.
        XmlTextWriter xmltw = new XmlTextWriter(FileName, new UTF8Encoding(false));
        document.WriteTo(xmltw);
        xmltw.Close();
    }
}
开发者ID:.NET开发者,项目名称:System.Security.Cryptography.Xml,代码行数:188,代码来源:XmlDsigXPathTransform


示例2: Main

//引入命名空间
using System;
using System.IO;
using System.Xml;
using System.Security.Cryptography;
using System.Security.Cryptography.Xml;

class Class1
{
    [STAThread]
    static void Main(string[] args)
    {
        // Encrypt a sample XML string.
        XmlDocument productsXml = LoadProducts();
        ShowTransformProperties(productsXml);

        // Encrypt an XPath Xml string.
        XmlDocument transformXml = LoadTransformByXml();
        ShowTransformProperties(transformXml);

        // Use XmlDsigXPathTransform to resolve a Uri.
        Uri baseUri = new Uri("http://www.contoso.com");
        string relativeUri = "xml";
        Uri absoluteUri = ResolveUris(baseUri, relativeUri);

        Console.WriteLine("This sample completed successfully; " +
            "press Enter to exit.");
        Console.ReadLine();
    }

    // Encrypt the text in the specified XmlDocument.
    private static void ShowTransformProperties(XmlDocument xmlDoc)
    {

        // Create a new XMLDocument object.
        XmlDocument doc = new XmlDocument();

        // Create a new XmlElement.
        XmlElement xPathElem = doc.CreateElement("XPath");

        // Set the element text to the value
        // of the XPath string.
        xPathElem.InnerText = "ancestor-or-self::PRODUCTS";

        // Create a new XmlDsigXPathTransform object.
        XmlDsigXPathTransform xmlTransform = new XmlDsigXPathTransform();

        // Load the XPath XML from the element. 
        xmlTransform.LoadInnerXml(xPathElem.SelectNodes("."));

        // Ensure the transform is using the proper algorithm.
        xmlTransform.Algorithm =
            SignedXml.XmlDsigXPathTransformUrl;

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

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

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

        // Verify the xmlTransform can accept the XMLDocument as an
        // input type.
        for (int i = 0; i < validInTypes.Length; i++)
        {
            if (validInTypes[i] == xmlDoc.GetType())
            {
                // Load the document into the transfrom.
                xmlTransform.LoadInput(xmlDoc);

                try
                {
                    // This transform is created for demonstration purposes.
                    XmlDsigXPathTransform secondTransform =
                        new XmlDsigXPathTransform();

                    string classDescription = secondTransform.ToString();

                    xmlTransform.LoadInnerXml(xPathElem.SelectNodes(".")); ;
                }
                catch (CryptographicException)
                {
                    Console.WriteLine("Caught exception while trying to " +
                        "load the specified Xml document. The document " +
                        "requires an XPath element to be valid.");
                }
                break;
            }
        }

        Type[] validOutTypes = xmlTransform.OutputTypes;

        for (int i = validOutTypes.Length - 1; i >= 0; i--)
        {
            if (validOutTypes[i] == typeof(System.Xml.XmlDocument))
            {
                try
                {
                    Type xmlDocumentType = typeof(System.Xml.XmlDocument);
                    XmlDocument xmlDocumentOutput = (XmlDocument)
                        xmlTransform.GetOutput(xmlDocumentType);

                    // Display to the console the Xml before and after
                    // encryption.
                    Console.WriteLine("Result of the GetOutput method call" +
                        " from the current transform: " +
                        xmlDocumentOutput.OuterXml);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Unexpected exception caught: " +
                        ex.ToString());
                }

                break;
            }
            else if (validOutTypes[i] == typeof(System.Xml.XmlNodeList))
            {
                try
                {
                    Type xmlNodeListType = typeof(System.Xml.XmlNodeList);
                    XmlNodeList xmlNodes = (XmlNodeList)
                        xmlTransform.GetOutput(xmlNodeListType);

                    // Display to the console the Xml before and after
                    // encryption.
                    Console.WriteLine("Encoding the following message: " +
                        xmlDoc.InnerText);

                    Console.WriteLine("Nodes of the XmlNodeList retrieved " +
                        "from GetOutput:");
                    for (int j = 0; j < xmlNodes.Count; j++)
                    {
                        Console.WriteLine("Node " + j +
                            " has the following name: " +
                            xmlNodes.Item(j).Name +
                            " and the following InnerXml: " +
                            xmlNodes.Item(j).InnerXml);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Unexpected exception caught: " +
                        ex.ToString());
                }

                break;
            }
            else
            {
                object outputObject = xmlTransform.GetOutput();
            }
        }
    }

    // Create an XML document for the dsig namespace.
    private static XmlDocument LoadTransformByXml()
    {
        XmlDocument xmlDoc = new XmlDocument();

        string transformXml = "<Signature><Reference URI=''><Transforms>";
        transformXml += "<Transform><XPath ";
        transformXml += "xmlns:dsig='http://www.w3.org/2000/09/xmldsig#'>";
        transformXml += "not(ancestor-or-self::dsig:Signature)";
        transformXml += "</XPath></Transform>";
        transformXml += "</Transforms></Reference></Signature>";

        xmlDoc.LoadXml(transformXml);
        return xmlDoc;
    }

    // Create an XML document describing various products.
    private static XmlDocument LoadProducts()
    {
        XmlDocument xmlDoc = new XmlDocument();

        string contosoProducts = "<PRODUCTS>";
        contosoProducts += "<PRODUCT><ID>123</ID>";
        contosoProducts += "<DESCRIPTION>Router</DESCRIPTION></PRODUCT>";
        contosoProducts += "<PRODUCT><ID>456</ID>";
        contosoProducts += "<DESCRIPTION>Keyboard</DESCRIPTION></PRODUCT>";
        contosoProducts += "<PRODUCT><ID>789</ID>";
        contosoProducts += "<DESCRIPTION>Monitor</DESCRIPTION></PRODUCT>";
        contosoProducts += "</PRODUCTS>";

        xmlDoc.LoadXml(contosoProducts);
        return xmlDoc;
    }

    // Resolve the specified base and relative Uri's .
    private static Uri ResolveUris(Uri baseUri, string relativeUri)
    {
        XmlUrlResolver xmlResolver = new XmlUrlResolver();
        xmlResolver.Credentials =
            System.Net.CredentialCache.DefaultCredentials;

        XmlDsigXPathTransform xmlTransform =
            new XmlDsigXPathTransform();
        xmlTransform.Resolver = xmlResolver;

        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;
    }
}
开发者ID:.NET开发者,项目名称:System.Security.Cryptography.Xml,代码行数:218,代码来源:XmlDsigXPathTransform



注:本文中的System.Security.Cryptography.Xml.XmlDsigXPathTransform类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# XmlDsigXsltTransform类代码示例发布时间:2022-05-24
下一篇:
C# XmlDsigExcC14NWithCommentsTransform类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap