views:

27

answers:

1

Hello,

I managed encrypting an xml document by encrypting an element and then replacing the element with the encrypted data. A shown in the sample code below.

Public Shared Sub Encrypt(ByVal textReader As TextReader, ByVal textWriter As TextWriter, ByVal certificateName As String)
    Dim xmlDoc As New XmlDocument()
    xmlDoc.Load(textReader)
    ' Add the schema from Resources
    AddSchema(xmlDoc)
    ' Get all elements to encrypt
    Dim elementsToEncrypt As List(Of XmlElement) = FindElementsToEncrypt(xmlDoc.DocumentElement)

    ' Get the certificate
    Dim certificate As X509Certificate2 = FindTrustedCertificate(certificateName)
    If certificate Is Nothing Then
        Throw New ArgumentException(String.Format("Certificate {0} not found", certificateName), "certificateName")
    End If

    Dim xmlEncrypter As New EncryptedXml(xmlDoc)

    ' Itterate all elelemts to encrypt
    For Each elementToEncrypt As XmlElement In elementsToEncrypt
        ' Encrypt the elements with the given certificate
        Dim encryptedData As EncryptedData = xmlEncrypter.Encrypt(elementToEncrypt, certificate)
        EncryptedXml.ReplaceElement(elementToEncrypt, encryptedData, False)
    Next

    ' Return the encrypted XmlDocument
    xmlDoc.Save(textWriter)
End Sub

This results in an xml where the element has EncryptedData, holding the X509 Certificate, like (I removed the bulk data):

      <EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element" xmlns="http://www.w3.org/2001/04/xmlenc#"&gt;
    <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#aes256-cbc" />
    <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#"&gt;
      <EncryptedKey xmlns="http://www.w3.org/2001/04/xmlenc#"&gt;
        <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5" />
        <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#"&gt;
          <X509Data>
            <X509Certificate>MIIFU......</X509Certificate>
          </X509Data>
        </KeyInfo>
        <CipherData>
          <CipherValue>dQOzeY81I9XAz......</CipherValue>
        </CipherData>
      </EncryptedKey>
    </KeyInfo>
    <CipherData>
      <CipherValue>qfmuwmyrpMOK.....</CipherValue>
    </CipherData>
  </EncryptedData>

If I encrypt 2 of those elements, the same X509 Certificate is included twice.

Does anybody know of a solution where the cerificate is for instance referenced?

Thanks,

Bert Heesbeen

A: 

Too bad nobody gave me the answer. It took me some time, but I managed myself.

I made code to generate a Rijndael session key. Use this key for every element to encrypt and reference this key. In the last EncryptedData element I include the rsa encrypted sessionkey and a reference to the x509 certificate.

This works. Bert

Bert Heesbeen