当前位置: 首页>>代码示例>>VB.NET>>正文


VB.NET XmlDsigXPathTransform类代码示例

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


在下文中一共展示了XmlDsigXPathTransform类的2个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的VB.NET代码示例。

示例1: SignVerifyEnvelope

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



Module SignVerifyEnvelope


    Sub Main(ByVal args() As String)
        ' Generate a signing key.
        Dim Key As 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...")
            Dim result As Boolean = VerifyXmlFile("SignedExample.xml")

            ' Display the results of the signature verification to \
            ' the console.
            If result Then
                Console.WriteLine("The XML signature is valid.")
            Else
                Console.WriteLine("The XML signature is not valid.")
            End If
        Catch e As CryptographicException
            Console.WriteLine(e.Message)
        Finally
            Key.Clear()
        End Try

    End Sub


    ' Sign an XML file and save the signature in a new file.
    Sub SignXmlFile(ByVal FileName As String, ByVal SignedFileName As String, ByVal Key As RSA, ByVal XPathString As String)
        ' Create a new XML document.
        Dim doc As 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.
        Dim signedXml As New SignedXml(doc)

        ' Add the key to the SignedXml document. 
        signedXml.SigningKey = Key

        ' Create a reference to be signed.
        Dim reference As New Reference()
        reference.Uri = ""

        ' Create an XmlDsigXPathTransform object using 
        ' the helper method 'CreateXPathTransform' defined
        ' later in this sample.
        Dim XPathTransform As XmlDsigXPathTransform = 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).
        Dim keyInfo As New KeyInfo()
        keyInfo.AddClause(New RSAKeyValue(CType(Key, RSA)))
        signedXml.KeyInfo = keyInfo

        ' Compute the signature.
        signedXml.ComputeSignature()

        ' Get the XML representation of the signature and save
        ' it to an XmlElement object.
        Dim xmlDigitalSignature As XmlElement = 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.
        Dim xmltw As New XmlTextWriter(SignedFileName, New UTF8Encoding(False))
        doc.WriteTo(xmltw)
        xmltw.Close()

    End Sub

    ' Verify the signature of an XML file and return the result.
    Function VerifyXmlFile(ByVal Name As String) As [Boolean]
        ' Create a new XML document.
        Dim xmlDocument As 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.
        Dim signedXml As New SignedXml(xmlDocument)

        ' Find the "Signature" node and create a new
        ' XmlNodeList object.
        Dim nodeList As XmlNodeList = xmlDocument.GetElementsByTagName("Signature")

        ' Load the signature node.
        signedXml.LoadXml(CType(nodeList(0), XmlElement))

        ' Check the signature and return the result.
        Return signedXml.CheckSignature()

    End Function


    ' Create the XML that represents the transform.
    Function CreateXPathTransform(ByVal XPathString As String) As XmlDsigXPathTransform
        ' Create a new XMLDocument object.
        Dim doc As New XmlDocument()

        ' Create a new XmlElement.
        Dim xPathElem As XmlElement = doc.CreateElement("XPath")

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

        ' Create a new XmlDsigXPathTransform object.
        Dim xForm As New XmlDsigXPathTransform()

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

        ' Return the XML that represents the transform.
        Return xForm

    End Function


    ' Create example data to sign.
    Sub CreateSomeXml(ByVal FileName As String)
        ' Create a new XmlDocument object.
        Dim document As New XmlDocument()

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

        ' Append the node to the document.
        document.AppendChild(node)

        ' Create a new XmlNode object.
        Dim subnode As XmlNode = 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.
        Dim xmltw As New XmlTextWriter(FileName, New UTF8Encoding(False))
        document.WriteTo(xmltw)
        xmltw.Close()

    End Sub
End Module
开发者ID:VB.NET开发者,项目名称:System.Security.Cryptography.Xml,代码行数:184,代码来源:XmlDsigXPathTransform

示例2: Class1

' 导入命名空间
Imports System.IO
Imports System.Xml
Imports System.Security.Cryptography
Imports System.Security.Cryptography.Xml



Class Class1

    <STAThread()> _
    Shared Sub Main(ByVal args() As String)
        ' Encrypt a sample XML string.
        Dim productsXml As XmlDocument = LoadProducts()
        ShowTransformProperties(productsXml)

        ' Encrypt an XPath Xml string.
        Dim transformXml As XmlDocument = LoadTransformByXml()
        ShowTransformProperties(transformXml)

        ' Use XmlDsigXPathTransform to resolve a Uri.
        Dim baseUri As New Uri("http://www.contoso.com")
        Dim relativeUri As String = "xml"
        Dim absoluteUri As Uri = ResolveUris(baseUri, relativeUri)

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

    End Sub


    ' Encrypt the text in the specified XmlDocument.
    Private Shared Sub ShowTransformProperties(ByVal xmlDoc As XmlDocument)
        ' Create a new XMLDocument object.
        Dim doc As New XmlDocument()

        ' Create a new XmlElement.
        Dim xPathElem As XmlElement = 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.
        Dim xmlTransform As 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.
        Dim xmlInTransform As XmlElement = xmlTransform.GetXml()
        Console.WriteLine(vbLf + "Xml representation of the current transform: ")
        Console.WriteLine(xmlInTransform.OuterXml)

        ' Retrieve the valid input types for the current transform.
        Dim validInTypes As Type() = xmlTransform.InputTypes
        ' Verify the xmlTransform can accept the XMLDocument as an
        ' input type.
        Dim i As Integer
        For i = 0 To validInTypes.Length
            If validInTypes(i).Equals(xmlDoc.GetType()) Then
                ' Load the document into the transfrom.
                xmlTransform.LoadInput(xmlDoc)
                Try
                    ' This transform is created for demonstration purposes.
                    Dim secondTransform As New XmlDsigXPathTransform()

                    Dim classDescription As String = secondTransform.ToString()
                    xmlTransform.LoadInnerXml(xPathElem.SelectNodes("."))
                Catch
                    Console.WriteLine("Caught exception while trying to " + "load the specified Xml document. The document " + "requires an XPath element to be valid.")
                End Try
                Exit For
            End If
        Next i

        Dim validOutTypes As Type() = xmlTransform.OutputTypes
        For i = validOutTypes.Length - 1 To 0 Step -1
            If validOutTypes(i).Equals(GetType(System.Xml.XmlDocument)) Then
                Try
                    Dim xmlDocumentType As Type = GetType(System.Xml.XmlDocument)
                    Dim xmlDocumentOutput As XmlDocument = CType(xmlTransform.GetOutput(xmlDocumentType), XmlDocument)
                    ' 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 ex As Exception
                    Console.WriteLine("Unexpected exception caught: " + ex.ToString())
                End Try

                Exit For
            ElseIf validOutTypes(i).Equals(GetType(System.Xml.XmlNodeList)) Then
                Try
                    Dim xmlNodeListType As Type = GetType(System.Xml.XmlNodeList)
                    Dim xmlNodes As XmlNodeList = CType(xmlTransform.GetOutput(xmlNodeListType), XmlNodeList)

                    ' 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 j As Integer = 0 To xmlNodes.Count - 1
                        Console.WriteLine("Node " + j + " has the following name: " + xmlNodes.Item(j).Name + " and the following InnerXml: " + xmlNodes.Item(j).InnerXml)
                    Next
                Catch ex As Exception
                    Console.WriteLine("Unexpected exception caught: " + ex.ToString())
                End Try

                Exit For
            Else
                Dim outputObject As Object = xmlTransform.GetOutput()
            End If 
        Next i

    End Sub


    ' Create an XML document for the dsig namespace.
    Private Shared Function LoadTransformByXml() As XmlDocument
        Dim xmlDoc As New XmlDocument()

        Dim transformXml As String = "<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

    End Function 'LoadTransformByXml


    ' Create an XML document describing various products.
    Private Shared Function LoadProducts() As XmlDocument
        Dim xmlDoc As New XmlDocument()

        Dim contosoProducts As String = "<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

    End Function 'LoadProducts


    ' Resolve the specified base and relative Uri's .
    Private Shared Function ResolveUris(ByVal baseUri As Uri, ByVal relativeUri As String) As Uri
        Dim xmlResolver As New XmlUrlResolver()
        xmlResolver.Credentials = System.Net.CredentialCache.DefaultCredentials

        Dim xmlTransform As New XmlDsigXPathTransform()
        xmlTransform.Resolver = xmlResolver
        Dim absoluteUri As Uri = xmlResolver.ResolveUri(baseUri, relativeUri)

        If Not (absoluteUri Is Nothing) Then
            Console.WriteLine(vbLf + "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")
        End If
        Return absoluteUri

    End Function
End Class
开发者ID:VB.NET开发者,项目名称:System.Security.Cryptography.Xml,代码行数:172,代码来源:XmlDsigXPathTransform


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