Peterson's Ponderings

Technical findings, ideas, thoughts and news directly from me.
in

Encrypted data in XML

It's been a few years since the W3C released the recommendation standard for XML Encryption within an XML document (http://www.w3.org/TR/xmlenc-core/).  To get the EncryptedData element into your XML was not very simple at all though, until now.  Visual Studio 2005 contains functions to support encrypting entire elements within a loaded XML document according to the XML standard.

The concept is pretty simple.  You have some confidential data in your XML that you don't want any Joe NetworkOp to read in the text file that you write somewhere to persist your data.  When you encrypt an element section, the element and all its contents are replaced with an EncryptedData element similar to the following:

    <EncryptedData Type='http://www.w3.org/2001/04/xmlenc#Element'
     xmlns='http://www.w3.org/2001/04/xmlenc#'>
      <CipherData>
        <CipherValue>A23B45C56</CipherValue>
      </CipherData>
    </EncryptedData>

To encrypt data in your XML document use the EncryptedXML class from the System.Security.Cryptography.Xml namespace.  There is an EncryptData and DecryptData method to perform the encryption.  You'll need to maintain the key that is used to encrypt/decrypt the data.  While the methods support encrypting the key into the EncryptedData result you still need to maintain the key that encrypts the key.  The EncryptedXML class accepts the key as a parameter on both the EncryptData and DecryptData methods.

MSDN has great sample code (http://msdn2.microsoft.com/en-us/library/system.security.cryptography.xml.encryptedxml.aspx) showing how easy it is to utilize encryption in an XML document.

Comments

Will said:

Hi there.  Good post.  I'm stuck at my org with having to use VS2003 .NET 1.1.  It unfortunately doesn't have the convenient XML encryption libs.  Any suggestions on how I should go about XML encryption in .NET 1.1?
# June 27, 2006 6:46 PM

dpeterson said:

Hi Will,
Well you can still use the EncryptedData XML standard you just have to parse/insert the elements properly yourself into the XML.  You'll also need to perform the encryption separately to get a CipherValue.  There are a ton of Triple DES and RSA encryption examples on the net which will help you encrypt your data (encryption is entirely too big a topic to get into in this blog comment) just be sure to convert the bytes resulting from the encryption into base64 which can be done easily with the System.Convert.ToBase64String (or convert back with System.Convert.FromBase64String).
# July 8, 2006 11:21 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)