First decide what encryption you want to use - RSA, SHA, etc...
For my example I will use a MD5/TripleDes.
Imports System.Security.Cryptography
Imports System.Text
Public Class CryptoZ
Private Shared DES As New TripleDESCryptoServiceProvider
Private Shared MD5 As New MD5CryptoServiceProvider
Public Shared Function MD5Hash(ByVal value As String) As Byte()
Return MD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(value))
End Function
Public Shared Function Encrypt(ByVal stringToEncrypt As String, ByVal key As String) As String
DES.Key = MD5Hash(key)
DES.Mode = CipherMode.ECB
Dim Buffer As Byte() = ASCIIEncoding.ASCII.GetBytes(stringToEncrypt)
Return Convert.ToBase64String(DES.CreateEncryptor().TransformFinalBlock(Buffer, 0, Buffer.Length))
End Function
Public Shared Function Decrypt(ByVal encryptedString As String, ByVal key As String) As String
Try
DES.Key = MD5Hash(key)
DES.Mode = CipherMode.ECB
Dim Buffer As Byte() = Convert.FromBase64String(encryptedString)
Return ASCIIEncoding.ASCII.GetString(DES.CreateDecryptor().TransformFinalBlock(Buffer, 0, Buffer.Length))
Catch
MessageBox.Show("Wrong Key Number, decryption not available!")
Return Nothing
End Try
End Function
End Class
Set up a valid XML format:
Dim sXML As String = "<?xml version=""1.0"" encoding=""utf-8"" ?>" sXML = String.Concat(sXML, Environment.NewLine, "<Root>") sXML = String.Concat(sXML, Environment.NewLine, " ", "<One />") sXML = String.Concat(sXML, Environment.NewLine, " ", "<Two />") sXML = String.Concat(sXML, Environment.NewLine, "</Root>")
Make the file:
Using sr As New StreamWriter({file path})
sr.Write(CryptoZ.Encrypt(sXML, "mykey"))
End Using
Open the file:
Using sr As New StreamReader({file path})
'tb is a textbox for viewing
tb.Text = CryptoZ.Encrypt(sr.ReadToEnd, "mykey")
End Using
Now lets make this a usable XML document:
Dim encryptedXmlFile As New XmlDocument
Using sr As New StreamReader({file path})
encryptedXmlFile.LoadXml(CryptoZ.Decrypt(sr.ReadToEnd, "mykey"))
End Using
Mod Edit: said:
{file path} is being used a indication to where the file is being loaded from. Replace it with the location must appropriate to you.
Now lets make some changes, using the normal ways you work with an XmlDocument:
For Each node As XmlNode In encryptedXmlFile.DocumentElement.ChildNodes 'lsb is a listbox, just to show the elements lsb.Items.Add(node.Name) 'make some changes node.InnerText = "test" Next
Now instead of calling encyrptedXmlFile.Save({file path}) cause we don't want to make the regular XML file, we do this:
Using sr As New StreamWriter({file path})
sr.Write(CryptoZ.Encrypt(encyrptedXmlFile.OuterXml, "mykey"))
End Using
The XmlDocument only exists in memory so no one can see it! Just call encyrptedXmlFile = Nothing when done. that it, enjoy!!!
This post has been edited by AdamSpeight2008: 01 May 2010 - 01:33 PM
Reason for edit:: Added a clarification.






MultiQuote








|