2010-08-25 59 views
0

我管理通過加密一個元素,然後用加密數據替換元素來加密一個XML文檔。 A顯示在下面的示例代碼中。加密一個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 

這導致在所述元件具有的EncryptedData一個xml,保持X509證書,如(I去除所述批量數據):

 <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證書包括兩次。

有沒有人知道一個解決方案,例如cerificate是參考?

感謝,

伯特Heesbeen

回答

0

太糟糕了,沒有人給我的答案。我花了一些時間,但我管理自己。

我做了生成Rijndael會話密鑰的代碼。對每個元素使用此密鑰來加密和引用此密鑰。在最後的EncryptedData元素中,我包含了rsa加密的sessionkey和對x509證書的引用。

This Works。 Bert