使用vb.net中的X509 Certificate2验证签名的XML文档

时间:2016-02-22 15:19:48

标签: xml vb.net x509certificate2

Private Sub VerifyButton_Click(sender As Object, e As EventArgs) Handles VerifyButton.Click


    ' 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.LoadXml(ToVerifyTextBox.Text)

    ' 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", "http://www.w3.org/2000/09/xmldsig#")


    If nodeList.Count <= 0 Then
        MessageBox.Show("Verification failed: No Signature was found in the document.")

        ' This example only supports one signature for
        ' the entire XML document.  Throw an exception 
        ' if more than one signature was found.
    ElseIf nodeList.Count >= 2 Then
        MessageBox.Show("Verification failed: More that one signature was found for the document.")
    Else

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

        ' Check the signature and show the result.
        '
        If signedXml.CheckSignature() Then
            MessageBox.Show("Signature verified!")
        Else
            MessageBox.Show("Invalid signature!!!")
        End If
    End If

End Sub

此代码将通过xml文件找到标记签名并验证签名是否有效,但我想检查并将密钥与xml文件中的密钥进行比较,如果没有,则签名验证为有效

1 个答案:

答案 0 :(得分:0)

我解决了这个问题。

这是我用来验证xml文档的代码:

Public Function VerifyXml(Doc As XmlDocument, Key As String) As Boolean

    Dim tmpRsa As New RSACryptoServiceProvider()

    tmpRsa.FromXmlString(Key)

    'VERIFY ALL ARGUMENTS HAVE BEEN PASSED IN 
    If Doc Is Nothing Then

        Throw New ArgumentException("Doc")
    End If

    If Key Is Nothing Then

        Throw New ArgumentException("Key")
    End If

    'HOLD THE SIGNED DOCUMENT 
    Dim signedXml As New SignedXml(Doc)

    'LOCATE THE SIGNATURE NODE IN THE DOCUMENT 
    Dim nodeList As XmlNodeList = Doc.GetElementsByTagName("Signature")

    'IF WE CANT FIND THE NODE THEN THIS DOCUMENT IS NOT SIGNED 
    If nodeList.Count <= 0 Then
        Throw New CryptographicException("Verification failed: No Signature was found in the document.")
    End If

    'IF THERE ARE MORE THEN ONE SIGNATURES THEN FAIL  
    If nodeList.Count >= 2 Then
        Throw New CryptographicException("Verification failed: More that one signature was found for the document.")
    End If

    'LOAD THE SIGNATURE NODE INTO THE SIGNEDXML DOCUMENT  
    signedXml.LoadXml(DirectCast(nodeList(0), XmlElement))

    'CHECK THE SIGNATURE AND SEND THE RESULT  
    Return signedXml.CheckSignature(tmpRsa)

End Function