Using DecryptDocument with Super-Encrypted Data

The EncryptedXml class comes with a nice utility method called DecryptDocument (For more information about using DecryptDocument check out my previous post introducing XML Encryption).  This method will decrypt all the EncryptedData elements it finds, assuming that it is able to figure out what key to use to perform the decryption with.  However, what happens if you use this method with some super encrypted data?

Super encryption is defined in the XML Encryption standard as encrypting an EncryptedData element (providing that you encrypt the entirety of the element).  In other words, it's encrypting already encrypted data.

The DecryptDocument method will decrypt all top-level EncryptedData elements, however if they are super-encrypted, it will not continue to loop over the document to decrypt the resulting EncryptedData.  If you want to fully decrypt a document containing super-encrypted data, you'll need to do this looping yourself.  (Or if you want to be sure that you've fully decrypted a document, and you can't be sure if it contains super encrypted data or not).

The code to do this is very simple, you just need to keep calling DecryptDocument while EncryptedData elements still exist.

while(doc.GetElementsByTagName("EncryptedData", EncryptedXml.XmlEncNamespaceUrl).Count > 0 )
    exml.DecryptDocument();