Export (0) Print
Expand All

How to: Encrypt XML Elements with Symmetric Keys

You can use the classes in the System.Security.Cryptography.Xml namespace to encrypt an element within an XML document. XML Encryption allows you to store or transport sensitive XML, without worrying about the data being easily read. This procedure decrypts an XML element using the Advanced Encryption Standard (AES) algorithm, also known as Rijndael.

For information about how to decrypt an XML element that was encrypted using this procedure, see How to: Decrypt XML Elements with Symmetric Keys.

When you use a symmetric algorithm like AES to encrypt XML data, you must use the same key to encrypt and decrypt the XML data. The example in this procedure assumes that the encrypted XML will be decrypted using the same key, and that the encrypting and decrypting parties agree on the algorithm and key to use. This example does not store or encrypt the AES key within the encrypted XML.

This example is appropriate for situations where a single application needs to encrypt data based on a session key stored in memory, or based on a cryptographically strong key derived from a password. For situations where two or more applications need to share encrypted XML data, consider using an encryption scheme based on an asymmetric algorithm or an X.509 certificate.

To encrypt an XML element with a symmetric key

  1. Generate a symmetric key using the RijndaelManaged class. This key will be used to encrypt the XML element.

    
    			RijndaelManaged key = null;
    
    			try
    			{
    				// Create a new Rijndael key.
    				key = new RijndaelManaged();
    
    
    
  2. Create an XmlDocument object by loading an XML file from disk. The XmlDocument object contains the XML element to encrypt.

    
    				// Load an XML document.
    				XmlDocument xmlDoc = new XmlDocument();
    				xmlDoc.PreserveWhitespace = true;
    				xmlDoc.Load("test.xml");
    
    
    
  3. Find the specified element in the XmlDocument object and create a new XmlElement object to represent the element you want to encrypt. In this example, the "creditcard" element is encrypted.

    
    			XmlElement elementToEncrypt = Doc.GetElementsByTagName(ElementName)[0] as XmlElement;
    
    
    
  4. Create a new instance of the EncryptedXml class and use it to encrypt the XmlElement with the symmetric key. The EncryptData method returns the encrypted element as an array of encrypted bytes.

    
    			EncryptedXml eXml = new EncryptedXml();
    
    			byte[] encryptedElement = eXml.EncryptData(elementToEncrypt, Key, false);
    
    
    
  5. Construct an EncryptedData object and populate it with the URL identifier of the XML Encryption element. This URL identifier lets a decrypting party know that the XML contains an encrypted element. You can use the XmlEncElementUrl field to specify the URL identifier.

    
    			EncryptedData edElement = new EncryptedData();
    			edElement.Type = EncryptedXml.XmlEncElementUrl;
    
    
    
  6. Create an EncryptionMethod object that is initialized to the URL identifier of the cryptographic algorithm used to generate the key. Pass the EncryptionMethod object to the EncryptionMethod property.

    
    			string encryptionMethod = null;
    
    			if (Key is TripleDES)
    			{
    				encryptionMethod = EncryptedXml.XmlEncTripleDESUrl;
    			}
    			else if (Key is DES)
    			{
    				encryptionMethod = EncryptedXml.XmlEncDESUrl;
    			}
    			if (Key is Rijndael)
    			{
    				switch (Key.KeySize)
    				{
    					case 128:
    						encryptionMethod = EncryptedXml.XmlEncAES128Url;
    						break;
    					case 192:
    						encryptionMethod = EncryptedXml.XmlEncAES192Url;
    						break;
    					case 256:
    						encryptionMethod = EncryptedXml.XmlEncAES256Url;
    						break;
    				}
    			}
    			else
    			{
    				// Throw an exception if the transform is not in the previous categories
    				throw new CryptographicException("The specified algorithm is not supported for XML Encryption.");
    			}
    
    			edElement.EncryptionMethod = new EncryptionMethod(encryptionMethod);
    
    
    
  7. Add the encrypted element data to the EncryptedData object.

    
    			edElement.CipherData.CipherValue = encryptedElement;
    
    
    
  8. Replace the element from the original XmlDocument object with the EncryptedData element.

    
    			EncryptedXml.ReplaceElement(elementToEncrypt, edElement, false);
    
    
    

This example assumes that a file named "test.xml" exists in the same directory as the compiled program. It also assumes that "test.xml" contains a "creditcard" element. You can place the following XML into a file called test.xml and use it with this example.

<root>
    <creditcard>
        <number>19834209</number>
        <expiry>02/02/2002</expiry>
    </creditcard>
</root>


using System;
using System.Xml;
using System.Security.Cryptography;
using System.Security.Cryptography.Xml;


namespace CSCrypto
{
	class Program
	{
		static void Main(string[] args)
		{
			RijndaelManaged key = null;

			try
			{
				// Create a new Rijndael key.
				key = new RijndaelManaged();
				// Load an XML document.
				XmlDocument xmlDoc = new XmlDocument();
				xmlDoc.PreserveWhitespace = true;
				xmlDoc.Load("test.xml");

				// Encrypt the "creditcard" element.
				Encrypt(xmlDoc, "creditcard", key);

				Console.WriteLine("The element was encrypted");

				Console.WriteLine(xmlDoc.InnerXml);

				Decrypt(xmlDoc, key);

				Console.WriteLine("The element was decrypted");

				Console.WriteLine(xmlDoc.InnerXml);

				
			}
			catch (Exception e)
			{
				Console.WriteLine(e.Message);
			}
			finally
			{
				// Clear the key.
				if (key != null)
				{
					key.Clear();
				}
			}

		}

		public static void Encrypt(XmlDocument Doc, string ElementName, SymmetricAlgorithm Key)
		{
			// Check the arguments.  
			if (Doc == null)
				throw new ArgumentNullException("Doc");
			if (ElementName == null)
				throw new ArgumentNullException("ElementToEncrypt");
			if (Key == null)
				throw new ArgumentNullException("Alg");

			////////////////////////////////////////////////
			// Find the specified element in the XmlDocument
			// object and create a new XmlElemnt object.
			////////////////////////////////////////////////
			XmlElement elementToEncrypt = Doc.GetElementsByTagName(ElementName)[0] as XmlElement;
			// Throw an XmlException if the element was not found.
			if (elementToEncrypt == null)
			{
				throw new XmlException("The specified element was not found");

			}

			//////////////////////////////////////////////////
			// Create a new instance of the EncryptedXml class 
			// and use it to encrypt the XmlElement with the 
			// symmetric key.
			//////////////////////////////////////////////////

			EncryptedXml eXml = new EncryptedXml();

			byte[] encryptedElement = eXml.EncryptData(elementToEncrypt, Key, false);
			////////////////////////////////////////////////
			// Construct an EncryptedData object and populate
			// it with the desired encryption information.
			////////////////////////////////////////////////

			EncryptedData edElement = new EncryptedData();
			edElement.Type = EncryptedXml.XmlEncElementUrl;

			// Create an EncryptionMethod element so that the 
			// receiver knows which algorithm to use for decryption.
			// Determine what kind of algorithm is being used and
			// supply the appropriate URL to the EncryptionMethod element.

			string encryptionMethod = null;

			if (Key is TripleDES)
			{
				encryptionMethod = EncryptedXml.XmlEncTripleDESUrl;
			}
			else if (Key is DES)
			{
				encryptionMethod = EncryptedXml.XmlEncDESUrl;
			}
			if (Key is Rijndael)
			{
				switch (Key.KeySize)
				{
					case 128:
						encryptionMethod = EncryptedXml.XmlEncAES128Url;
						break;
					case 192:
						encryptionMethod = EncryptedXml.XmlEncAES192Url;
						break;
					case 256:
						encryptionMethod = EncryptedXml.XmlEncAES256Url;
						break;
				}
			}
			else
			{
				// Throw an exception if the transform is not in the previous categories
				throw new CryptographicException("The specified algorithm is not supported for XML Encryption.");
			}

			edElement.EncryptionMethod = new EncryptionMethod(encryptionMethod);

			// Add the encrypted element data to the 
			// EncryptedData object.
			edElement.CipherData.CipherValue = encryptedElement;

			////////////////////////////////////////////////////
			// Replace the element from the original XmlDocument
			// object with the EncryptedData element.
			////////////////////////////////////////////////////
			EncryptedXml.ReplaceElement(elementToEncrypt, edElement, false);
		}

		public static void Decrypt(XmlDocument Doc, SymmetricAlgorithm Alg)
		{
			// Check the arguments.  
			if (Doc == null)
				throw new ArgumentNullException("Doc");
			if (Alg == null)
				throw new ArgumentNullException("Alg");

			// Find the EncryptedData element in the XmlDocument.
			XmlElement encryptedElement = Doc.GetElementsByTagName("EncryptedData")[0] as XmlElement;

			// If the EncryptedData element was not found, throw an exception.
			if (encryptedElement == null)
			{
				throw new XmlException("The EncryptedData element was not found.");
			}

			
			// Create an EncryptedData object and populate it.
			EncryptedData edElement = new EncryptedData();
			edElement.LoadXml(encryptedElement);

			// Create a new EncryptedXml object.
			EncryptedXml exml = new EncryptedXml();
			

			// Decrypt the element using the symmetric key.
			byte[] rgbOutput = exml.DecryptData(edElement, Alg);

			// Replace the encryptedData element with the plaintext XML element.
			exml.ReplaceData(encryptedElement, rgbOutput);

		}

	}


}


Never store a cryptographic key in plaintext or transfer a key between machines in plaintext. Instead, use a secure key container to store cryptographic keys.

When you are done using a cryptographic key, clear it from memory by setting each byte to zero or by calling the Clear method of the managed cryptography class.

Community Additions

ADD
Show:
© 2014 Microsoft