【问题标题】:Encrypting multiple elements of one xml document加密一个xml文档的多个元素
【发布时间】:2010-08-25 13:29:29
【问题描述】:

我通过加密一个元素然后用加密数据替换该元素来管理加密一个 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 证书。

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

谢谢,

伯特·希斯宾

【问题讨论】:

    标签: .net xml vb.net encryption


    【解决方案1】:

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

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

    这行得通。 伯特

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-22
      • 1970-01-01
      • 2012-02-09
      • 1970-01-01
      • 2014-03-23
      • 1970-01-01
      相关资源
      最近更新 更多