It has been a long time since my last. I hope to do better.
Lately I’ve been working on a feature for our system which requires our server to keep some of data encrypted. When accessed by a client, the server returns an XML formatted result where some of the nodes are encrypted. Below is an example:
<books>
<book>
<EncryptedNode IV="abcdefg">AES-256-CBC|8c9cba4110124ceabe672d9ce345a3b8|6NxJchrB/fmN8ab0m4EPnJ3XS2ek0z4dqVmKtZf6LGA=</EncryptedNode>
</book>
</books>
On the client side, I wrote a method which retrieves the XML from the server and replaces the encrypted nodes with their decrypted values. The example above results in the following decrypted XML:
<books>
<book>
<title>title1</title>
</book>
</books>
So far so good. My confusion was with the implementation details. To replace the encrypted node I overwrote the InnerText property of the parent node as shown below (I know this isn’t an optimized method for DOM manipulation, but it seems to be the simplest one).
String encryptedText = node.InnerText; // encryptedText = "AES-256-CBC|..."
String decryptedText = DecryptText(myKey, encryptedText); // decrypedText = "<title>title1</title>"
node.ParentNode.InnerText = decryptedText;
Although this looked right at first, it did not result in what I expected. Instead of adding a child node named ‘title’ to the node named ‘book’, what I really did was change the inner text of the ‘book’ node to “<title>title1</title>”. Replacing node.ParentNode.InnerText with node.ParentNode.InnerXml solved my problem.
The MSDN documentation is a bit confusing regarding the differences between these two properties (in my example value is null).
XmlNode.InnerText: Gets or sets the concatenated values of the node and all its child nodes. XmlNode.InnerXml: Gets or sets the markup representing only the child nodes of this node
Running some tests I came to the conclusion that InnerText escapes all characters, while InnerXml does not. Goes without saying that you need to make sure to use the right one. Also, note that if using InnerXml the string must be valid XML as the characters will not be formatted.
I hope this helps someone.

Recent Comments