Decrypting the XML Document
You need to go through the following steps to decrypt the XML element that you earlier encrypted:
- Load the XML document "encryptedorder.xml." Note that this time around you need to load the encrypted document you generated earlier, not "order.xml."
Dim encryptedDoc As New XmlDocument()
- Retrieve the encrypted XML element by retrieving the EncryptedData tag. The EncryptedData tag is used to store any encrypted data.
Here you need to do a type cast to XmlElement. Because the GetElementsByTagName returns a NodeList, I decided to take the first element by specifying (0).
Dim encryptedElement As XmlElement = _
- Create an encrypted data object and
- Load the encrypted element into it.
Dim ed2 As New EncryptedData()
- Create an encrypted XML object.
Dim exml2 As New EncryptedXml()
- Decrypt the encrypted data element using the key and calling the DecryptData method of the EncryptedXML object.
Dim decryptedBilling As Byte() = exml2.DecryptData(ed2, tDESkey)
- Replace the encrypted element with the plain-text XML element.
- Save the decrypted data to a file.
Build the project and run it. You now have three files: the original "Order.xml," the encrypted "encryptedorder.xml," and the new "DecryptedOrder.xml" document, which would be created when the program runs.
You're just encrypted and decrypted a portion of an XML file and at the same time if you desire you could encrypt/decrypt the entire file. The EncryptedXML class makes this extremely easy to do.
Storing the Key
The above example encrypted and decrypted the "order.xml" file in the same module. You might want to store the key used to encrypt the file in a text file that is shared between the sender and the receiver of the encrypted data.
The key generated by the TripleDESCryptoServiceProvider is a byte array. Hence, to store it to a file one would need to convert it to an equivalent string representation (as shown below) first, and then store it to a text file.
Dim sharedkey As New TripleDESCryptoServiceProvider()
'Save this key to disk to enable the recipient to decrypt
Dim writer2 As IO.StreamWriter =_
Dim str As String = Convert.ToBase64String(sharedkey.Key)
While decrypting you would have to similarly retrieve this shared key from the file and then use it as the key to decrypt the XML document. In the source code provided with this article (see left column), I've included an example to illustrate this method. There are two separate files: one to encrypt the XML and one to decrypt it.