X509Certificate encryption/decryption
Asked Answered
B

1

7

I'm just starting to learn XML security. We have VS-2005 & ASP.Net 2.0. I want to send XML to a outside URL and it needs to be encrypted. I'm doing exactly what the MSDN articles ms229744 & ms229943 are doing, but when doing the DecryptDocument() method, I keep getting the "Unable to retrieve the decryption key." I'm using our SSL web certificate, and I currently use X509Certificate to digitally sign the XML and it works fine.

I also asked somebody else to try this from a different shop and they are getting the same error. Is there a documented problem with the X509 decryption methods? In test code below, I'm posting the XML to another web page that is attempting to decrypt the XML. What I don't understand is how the DecryptDocument() method can work if it doesn't even check to see if the Public key is embedded. Is this the problem? If so, how do I check to make sure it is embedded in the XML? Any help is appreciated. Thanks!

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

Borneol answered 29/5, 2009 at 16:34 Comment(0)
T
0

Chances are, your web process can't access the private key. I ran into the same thing once, and posted an answer in this item:

Set read permission for certificate from command line

In case you still have issues, for our encryption routines, we referenced http://msdn.microsoft.com/en-us/magazine/cc163454.aspx

Tallis answered 1/9, 2011 at 19:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.