How to: Decrypt XML Elements with Symmetric Keys
You can use the classes in thenamespace 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 code example decrypts an XML element using the Advanced Encryption Standard (AES) algorithm, also known as Rijndael.
For information about how to encrypt an XML element using this procedure, see.
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 was encrypted 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 decrypt an XML element with a symmetric key
Encrypt an XML element with the previously generated key using the techniques described in.
Find the <EncryptedData> element (defined by the XML Encryption standard) in anobject that contains the encrypted XML and create a new object to represent that element.
Create anobject by loading the raw XML data from the previously created XmlElement object.
Create a newobject and use it to decrypt the XML data using the same key that was used for encryption.
Replace the encrypted element with the newly decrypted plaintext element within the XML document.
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>
Compiling the Code
To compile this example, you need to include a reference to System.Security.dll.
Include the following namespaces:, , and System.Security.Cryptography.Xml.
Never store a cryptographic key in plaintext or transfer a key between machines in plaintext.
When you are done using a symmetric cryptographic key, clear it from memory by setting each byte to zero or by calling themethod of the managed cryptography class.