Xml
Imports System
Imports System.Security.Cryptography
Imports System.Security.Cryptography.Xml
Imports System.Xml
Public Class Form1
Private Sub Form1_Load (ByVal sender as System.Object, ByVal e as System.EventArgs) Handles Mybase.lo Ad
' Create a new CspParameters object to specify
& nbsp; ' a key container.
Dim Cspparams as New cspparameters ()
cspparams.keycontainername = "Xml_dsig_rsa_key"
" Create a new RSA signing key and save it in the container.
Dim Rsakey as New RSACryptoServiceProvider (cspparams)
' Create a new XML document.
Dim xmldoc as New XmlDocument ()
' Load an XML file into the XmlDocument object.
Xmldoc.preservewhitespace = True
Xmldoc.loadxml ("<text> can use a class in the System.Security.Cryptography.Xml namespace to sign the XML ' document or part of an XML document by digital signature </text > ")
' Sign the XML document.
Signxml (xmldoc, Rsakey)
MsgBox ("XML file signed.")
' Save the document.
Xmldoc.save ("C:\ok.xml")
MsgBox (Verifyxml (xmldoc, Rsakey))
End Sub
' Sign an XML file.
' This document cannot be verified unless the verifying
' Code has the key with which it is signed.
Sub Signxml (ByVal Doc as XmlDocument, ByVal Key as RSA)
' Check arguments.
If Doc is nothing Then
Throw New ArgumentException ("Doc")
End If
If Key is nothing Then
Throw New ArgumentException ("Key")
End If
' 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 = ""
' Add an enveloped transformation to the reference.
Dim env as New xmldsigenvelopedsignaturetransform ()
Reference. AddTransform (ENV)
' 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 a XmlElement object.
Dim xmldigitalsignature as XmlElement = Signedxml.getxml ()
' Append the element to the XML document.
Doc.DocumentElement.AppendChild (Doc.importnode (Xmldigitalsignature, True))
End Sub
Function Verifyxml (ByVal Doc as XmlDocument, ByVal Key as RSA) as [Boolean]
' Check arguments.
If Doc is nothing Then
Throw New ArgumentException ("Doc")
End If
If Key is nothing Then
Throw New ArgumentException ("Key")
End If
' Create a new SignedXml object and pass it
' The XML document class.
Dim SignedXml as New signedxml (DOC)
' Find the ' Signature ' node and create a new
' XmlNodeList object.
Dim nodelist as XmlNodeList = Doc.getelementsbytagname ("Signature")
' Throw an exception if no signature is found.
If nodelist.count <= 0 Then
MsgBox ("Verification failed:no Signature is found in the document.")
End If
' This example only supports one signature for
' The entire XML document. Throw an exception