加密一个xml文档的多个元素

时间:2010-08-25 13:29:30

标签: .net xml vb.net encryption

我通过加密元素然后用加密数据替换元素来管理加密xml文档。如下面的示例代码所示。

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

这导致xml元素具有EncryptedData,持有X509证书,就像(我删除了批量数据):

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

如果我对其中的2个元素进行加密,则会包含两次相同的X509证书。

有人知道例如引用证书的解决方案吗?

谢谢,

Bert Heesbeen

1 个答案:

答案 0 :(得分:0)

太糟糕没有人给我答案。 我花了一些时间,但我自己做了。

我制作了代码来生成Rijndael会话密钥。对每个元素使用此密钥来加密和引用此密钥。在最后一个EncryptedData元素中,我包含了rsa加密的sessionkey和对x509证书的引用。

这很有效。 伯特