Persisting a dataset as encrypted XML

I had to revisit this functionality today. I am pretty certain that I tested decrypting back to a dataset with the previous method I was using, but today it just wouldn’t work at all. After a lot of reading, googling and research, I learned a lot about various methods of cryptography, yet I was still unable to solve my problem on my own. Finally I came upon a code sample (not in the first 4 searches, mind you!) and thought I better persist THAT here!! Here is the link. If for some reason that link goes away here’s my particular (VB.Net) treatment of the code:

Public Sub encryptDS(ByVal ds As DataSet, ByVal filename As String)
Dim aCryptoStream As
CryptoStream
Try
 Dim aXmlTextWriter As
XmlTextWriter
 aXmlTextWriter = New
XmlTextWriter(filename, Text.Encoding.UTF8)
 Dim aUE As New
Text.UnicodeEncoding
 Dim keyBytes() As Byte
= {……} ‘your secret bytes go here
 Dim RMCrypto As RijndaelManaged = New
RijndaelManaged
 aCryptoStream = New
CryptoStream(aXmlTextWriter.BaseStream,  RMCrypto.CreateEncryptor(keyBytes, keyBytes), CryptoStreamMode.Write)
 
ds.WriteXml(aCryptoStream)
Catch ex As
Exception
 …
Finally
 aCryptoStream.Close()
End Try
End Sub

Public Sub DecryptDS(ByRef ds As DataSet, ByVal filename As String)
 Dim aFileStream As New
FileStream(filename, FileMode.Open)
 Dim aStreamReader As
StreamReader
 Try
  aStreamReader = New
StreamReader(aFileStream)
  Dim aUE As New
Text.UnicodeEncoding
  Dim keyBytes() As Byte
= {….} ‘ your secret bytes go here
  Dim RMCrypto As RijndaelManaged = New
RijndaelManaged
  Dim aCryptoStream As New CryptoStream(aFileStream,
  RMCrypto.CreateDecryptor(keyBytes, keyBytes), CryptoStreamMode.Read)
  ‘Restore the data set
  ds.ReadXml(aCryptoStream)
 Catch exS As
IOException
  …
 Catch ex As
Exception
  …
 Finally
  aStreamReader.Close()
  aFileStream.Close()
 End Try
End Sub

 

  Sign up for my newsletter so you don't miss my conference & Pluralsight course announcements!  

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.