X509证书加密/解密

时间:2009-05-29 16:34:55

标签: xml encryption-asymmetric

我刚开始学习XML安全性。我们有VS-2005& ASP.Net 2.0。我想将XML发送到外部URL并且需要加密。我正在做的MSDN文章ms229744& ms229943正在做,但在执行DecryptDocument()方法时,我不断收到“无法检索解密密钥”。我正在使用我们的SSL Web证书,我目前使用X509Certificate对XML进行数字签名,它运行正常。

我还要求其他人在不同的商店尝试这个,他们也会遇到同样的错误。是否存在X509解密方法的文档问题?在下面的测试代码中,我将XML发布到另一个试图解密XML的网页。我不明白的是,如果DecryptDocument()方法甚至不检查是否嵌入了公钥,它是如何工作的。这是问题吗?如果是这样,我如何检查以确保它嵌入在XML中?任何帮助表示赞赏。谢谢!

Private Function EncryptXml(ByVal xmlDoc As XmlDocument, ByVal Cert As X509Certificates.X509Certificate2) As XmlDocument

   Dim dataNodes As XmlNodeList = xmlDoc.SelectNodes("Agency")
   If dataNodes.Count <> 1 Then
       Return Nothing 
   End If  
   Dim elementToEncrypt As XmlElement = CType(xmlDoc.GetElementsByTagName("Agency")(0), XmlElement)
   Dim eXml As New EncryptedXml()
   Dim Key As RSACryptoServiceProvider = CType(Cert.PrivateKey, RSACryptoServiceProvider)
   Dim edElement As EncryptedData = eXml.Encrypt(elementToEncrypt, Cert)
   EncryptedXml.ReplaceElement(elementToEncrypt, edElement, False)
   Return xmlDoc 
End Function



Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 
If Not IsPostBack Then
   If Request.Form("hdnSignedXML") IsNot Nothing Then
   Dim strXML As String = Request.Form("hdnSignedXML")
   Dim xmlDoc As New XmlDocument
   xmlDoc.LoadXml(strXML)
   xmlDoc.PreserveWhitespace = True
   Response.ContentType = "text/plain"
   Response.Write(strXML)

   Dim exml As New Xml.EncryptedXml(xmlDoc)
   exml.DecryptDocument()
   xmlDoc.Save("C:/inetpub/TestExampleDecrypted.xml")


   Response.End()

End If

End Sub

JP

1 个答案:

答案 0 :(得分:0)

很可能,您的网络进程无法访问私钥。我遇到过同样的事情,并在这个项目中发了一个答案:

Set read permission for certificate from command line

如果您仍有问题,我们的加密例程会引用http://msdn.microsoft.com/en-us/magazine/cc163454.aspx