4. Verifying an XML Signature
Begin verifying the signature by loading the XML Signature document
(which you have saved as the file xmlsig.xml)
into an instance of the SignedXml class:
# C#
// load the XML document
XmlDocument x_xml_doc = new XmlDocument( );
x_xml_doc.Load("xmlsig.xml");
// create the SignedXml instance
SignedXml x_signed_xml = new SignedXml( );
// get the node list from the XML sig doc
XmlNodeList x_node_list = x_xml_doc.GetElementsByTagName("Signature");
// load the XML signature document
x_signed_xml.LoadXml((XmlElement)x_node_list[0]);
# Visual Basic .NET
' load the XML document
Dim x_xml_doc As XmlDocument = New XmlDocument( )
x_xml_doc.Load("xmlsig.xml")
' create the SignedXml instance
Dim x_signed_xml As SignedXml = New SignedXml( )
' get the node list from the XML sig doc
Dim x_node_list As XmlNodeList = x_xml_doc.GetElementsByTagName("Signature")
' load the XML signature document
x_signed_xml.LoadXml(CType(x_node_list(0), XmlElement))
You need to create the asymmetric algorithm that will be used to
verify the signature; you should configure the algorithm class with
the public parameters from the key pair that was used to generate the
signature.
Once you have created the algorithm, create an instance of the
KeyInfo class, which accepts an instance of either
the DSAKeyValue or RSAKeyValue
class, depending on which algorithm has been used. Configure the
SignedXml class to use the asymmetric algorithm by
setting the value of the KeyInfo property:
# C#
// create a new instance of the DSA algorithm
DSA x_dsa = DSA.Create( );
// configure the signing key
// ...
// create the KeyInfo instance
KeyInfo x_info = new KeyInfo( );
// add the DSA instance to the KeyInfo
x_info.AddClause(new DSAKeyValue(x_dsa));
// configure the SignedXml class to use the
// DSA keys for verification
x_signed_xml.KeyInfo = x_info;
# Visual Basic .NET
' create a new instance of the DSA algorithm
Dim x_dsa As DSA = DSA.Create( )
' configure the signing key
' ...
' create the KeyInfo instance
Dim x_info As KeyInfo = New KeyInfo( )
' add the DSA instance to the KeyInfo
x_info.AddClause(New DSAKeyValue(x_dsa))
' configure the SignedXml class to use the
' DSA keys for verification
x_signed_xml.KeyInfo = x_info
Finally, verify the signature by calling the
CheckSignature method of the
SignedXml class; this method returns
true if the signature is valid and
false if it is not:
# C#
// verify the signature
bool x_signature_valid = x_signed_xml.CheckSignature( );
# Visual Basic .NET
' verify the signature
Dim x_signature_valid As Boolean = x_signed_xml.CheckSignature( )