There are multiple types of encryption we can select from but for this example I will use Triple DES. Other encryption types are:
- AES 128
- AES 192
- AES 256
- RSA
- X509CertificateEx
To avail of the .NET encryption, we need to include the following namespaces on our VB.NET project:
Imports System.Security.Cryptography
Imports System.Security.Cryptography.Xml
Visual Studio 2005 has an issue on System.Security.Cryptography.Xml. Framework 2.0 does not recognize such namespace. I personally don't know the reason behind the compiler's error but there is always a workaround. Just add a reference to System.Security in your project.
For this project, we will use the following XML document named as "sample.xml" (also include on the downloaded project files):
<purchase>
<items>
<item quantity="1">XML Encrpytion on .NET</item>
<item quantity="1">XML Encrpytion on .NET Workshop</item>
<item quantity="1">Visual Studio 2005 Team Edition</item>
</items>
<shipping>
<buyer>Fryan Valdez</buyer>
<streetaddress>319 Joseph St. Annex 41</streetaddress>
<cityaddress>Manila</cityaddress>
<country>Philippines</country>
<zipcode>1772</zipcode>
</shipping>
<billing>
<paymentInfo type="Mastercard">
<number>9999-9999-9999-9999</number>
<expirationDate>04/21/10</expirationDate>
<billingAddress>
<who>Fryan Digital World</who>
<streetaddress>www.fryan0911.com</streetaddress>
<cityaddress>wwww</cityaddress>
<zipcode>0911</zipcode>
</billingAddress>
</paymentInfo>
</billing>
</purchase>
On our encryption method, we will encrypt the whole "billing" element:
<billing>
<paymentInfo type="Mastercard">
<number>9999-9999-9999-9999</number>
<expirationDate>04/21/10</expirationDate>
<billingAddress>
<who>Fryan Digital World</who>
<streetaddress>www.fryan0911.com</streetaddress>
<cityaddress>wwww</cityaddress>
<zipcode>0911</zipcode>
</billingAddress>
</paymentInfo>
</billing>
Here is the VB.NET Code to encrypt the element. Please read the comments (in green) carefully for the detailed description of each line. You can put this code on your Encrypt button like the one included on the downloadable project.
Dim xmldoc As New XmlDocument()
Try
xmldoc.Load("sample.xml") 'Load XML
Dim tDESkey As New TripleDESCryptoServiceProvider()
'Create the shared key and save it to disk to enable the receiver to decrypt
Dim sharedkey As New TripleDESCryptoServiceProvider()
Dim writer2 As IO.StreamWriter = New IO.StreamWriter("sharedsampleKey.txt")
Dim str As String = Convert.ToBase64String(sharedkey.Key)
writer2.WriteLine(str)
writer2.Close()
Dim exml As EncryptedXml = New EncryptedXml(xmldoc)
'Select the XML node/element to be encrpyted
Dim encryptElement As XmlElement = CType(xmldoc.SelectSingleNode("/purchase/billing"), XmlElement)
'Encrypt the XML element data using the TripleDES alogrithm and save the results into a byte array
Dim encryptXML As Byte() = exml.EncryptData(encryptElement, sharedkey, False)
' Create an EncryptedData object and populate it.
Dim ed As New EncryptedData()
ed.Type = EncryptedXml.XmlEncElementUrl
ed.EncryptionMethod = New EncryptionMethod(EncryptedXml.XmlEncTripleDESUrl)
' Create a CipherData element and replace the current text value of element we want to encrypt
ed.CipherData = New CipherData()
ed.CipherData.CipherValue = encryptXML
EncryptedXml.ReplaceElement(encryptElement, ed, False)
'Save the encrypted version of XML to disk
xmldoc.Save("encryptedsample.xml")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
The encryption code will create two files:
1. sharedsampleKey.txt - need by the recipient for decryption
2. encryptedsample.xml - the encrypted XML file
Here is the sample file (encryptedsample.xml) after encryption:
<purchase>
<items>
<item quantity="1">XML Encrpytion on .NET</item>
<item quantity="1">XML Encrpytion on .NET Workshop</item>
<item quantity="1">Visual Studio 2005 Team Edition</item>
</items>
<shipping>
<buyer>Fryan Valdez</buyer>
<streetaddress>319 Joseph St. Annex 41</streetaddress>
<cityaddress>Manila</cityaddress>
<country>Philippines</country>
<zipcode>1772</zipcode>
</shipping>
<EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element" xmlns="http://www.w3.org/2001/04/xmlenc#">
<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlen
c#tripledes-cbc" />
<CipherData>
<CipherValue>rdUGco9lxMEP4A/uTh6lvrb6aZbQxXIAYcGnfsuzbl
NNuDMYw6FpLA5oYgyRjfiwVJ0sv9rmtHpO6sBjCpF9Y5paOh0
/ViEeQp4ZLFHWRrFQ/5oKfPnOrIrX42ewfxrfe2Rsbe
cAyuaetyHM7IF05gZkhr
/OZC7/d2fBDASjInX8Vk/OquiV5Cr388l7H80r9fyHtk1qdmCUPqdpyN
/IPhRFfxXmHhYzhcFpVppLjzUXiO91129qFTBH3E+M+LS5WeQFlI
wYfptqDEz35Ez263lfoySqSampY76
+pg7LSOW54ZNIal1M0o0RSaacBU0JiaIh0HiYEWaw
/S/Fpn5Sv46smq1m2Gm4BOAhQq
/BVXs7+7MxPJN+ynBUsAqTL15+gti0r277um3ySgjpXJvpItq7
PHt+NlyEqfbIq1aUW5w=&
lt;/CipherValue>
</CipherData>
</EncryptedData>
</purchase>
You can notice that the billing element now contains encrypted values.
To decrypt the file (usually the recipient application will do this), use the following code:
Try
Dim sharedkey As New TripleDESCryptoServiceProvider()
'Retrieve shared key and assign to the TripleDESCryptoServiceProvider object
Dim rd As IO.StreamReader = New IO.StreamReader("sharedsampleKey.txt")
Dim bytedata() As Byte = Convert.FromBase64String(rd.ReadToEnd())
sharedkey.Key = bytedata
Dim encryptedDoc As New XmlDocument()
encryptedDoc.Load("encryptedsample.xml")
' XmlElement object.
Dim EncryptedElement As XmlElement = CType(encryptedDoc.GetElementsByTagName("EncryptedData")(0), XmlElement)
' Create an EncryptedData object and populate it.
Dim ed As New EncryptedData()
ed.LoadXml(EncryptedElement)
' Decrypt the element using the attached shared key
Dim encryptXML As New EncryptedXml()
Dim decryptedXML As Byte() = encryptXML.DecryptData(ed, sharedkey)
' Replace the encryptedData element with the original text value.
encryptXML.ReplaceData(EncryptedElement, decryptedXML)
encryptedDoc.Save("decryptedsample.xml")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Take note that the decryption method needs the "sharedsampleKey.txt" to decrypt the encrypted XML file. Decryption code will create a new file named as "decryptedsample.xml". It contains the original content without encryption.
You can download the full sourcecode of the project at mediafire
1 comments:
Never mind the question I posted on Digital sign. Here's exactly what I need. Kudos to you!
Post a Comment