473,385 Members | 2,015 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Dataset encryption

I made this class to encrypt my DataSet before saving it
to disk. So, first in the main program I write the
DataSet to XML in a MemoryStream. I pass this stream to
the E_File sub, which encrypts the stream and writes it
out to the FileStream. Now, in the D_File function, I
read the encrypted file into a FileStream, then decrypt
it into a MemoryStream, which I pass back to my DataSet
and Read the XML into the DataSet. The problem I'm
having, is somewhere I'm losing the last 2 bytes of the
file, so if my DataSet is named "NewDataSet", the end of
the file looks like </NewDataSe
I'm not sure where these two bytes are being lost at, and
if anyone could point out my blunder, I can stop beating
my head into walls and keyboards!
Below is my code for the encryption class:

Imports System
Imports System.Text
Imports System.IO
Imports System.Security
Imports System.Security.Cryptography

Public Class Perculate
Public Event Callback(ByVal Msg As String)
Public Event Bytes_Processed(ByVal Curr As Long,
ByVal Total As Long)
Protected IV() As Byte = New Byte() {0, 0, 0, 0, 0,
0, 0, 0}

Public Function D_File(ByVal InFile As String, ByVal
key As String) As Stream
Dim fin As New FileStream(InFile, FileMode.Open,
FileAccess.Read)
Dim _ms As New MemoryStream(fin.Length)

Dim bin(100) As Byte
Dim redlin As Long = 0
Dim totlen As Long = fin.Length
Dim len As Integer

If key.Length < 24 Then key = New String("0", 24 -
key.Length) & key

Try
Dim tdes As New TripleDESCryptoServiceProvider
()
Dim decStream As New CryptoStream(_ms, _
tdes.CreateDecryptor
(Text.ASCIIEncoding.ASCII.GetBytes(key), _
IV), _
CryptoStreamMode.Write)
RaiseEvent Callback("Decrypting")

fin.Position = 0

Do
len = fin.Read(bin, 0, bin.Length)
decStream.Write(bin, 0, len)
redlin += len
RaiseEvent Bytes_Processed(redlin, totlen)
If len = 0 Then Exit Do
Loop
Return _ms
Catch ex As CryptographicException
RaiseEvent Callback(ex.Message)
End Try
End Function

Public Sub E_File(ByVal InData As Stream, ByVal
Outfile As String, ByVal Key As String)
If File.Exists(Outfile) Then File.Delete(Outfile)
Dim fout As New FileStream(Outfile,
FileMode.CreateNew, FileAccess.Write)

fout.SetLength(0)

Dim bin(100) As Byte
Dim redlin As Long = 0
Dim totlen As Long = InData.Length + 2
Dim len As Integer
Dim hByte() As Byte = ASCIIEncoding.ASCII.GetBytes
("<?xml version=" & Chr(34) & "1.0" & Chr(34) & "
standalone=" & Chr(34) & "yes" & Chr(34) & "?>" & vbCrLf)

If Key.Length > 24 Then
RaiseEvent Callback("Key must be 24 or less
characters!")
Exit Sub
ElseIf Key.Length < 6 Then
RaiseEvent Callback("Key must be 6 or more
characters!")
Exit Sub
End If
If Key.Length < 24 Then Key = New String("0", 24 -
Key.Length) & Key
Try
Dim tdes As New TripleDESCryptoServiceProvider
()
If Not tdes.IsWeakKey
(Text.ASCIIEncoding.ASCII.GetBytes(Key)) Then
Dim encStream As New CryptoStream(fout, _
tdes.CreateEncryptor
(Text.ASCIIEncoding.ASCII.GetBytes(Key), _
IV),
_
CryptoStreamMode.Write)

RaiseEvent Callback("Encrypting")

InData.Position = 0
'Force it to write out the XML header info
encStream.Write(hByte, 0, hByte.Length)
Do
len = InData.Read(bin, 0, bin.Length)
encStream.Write(bin, 0, len)
redlin += len
RaiseEvent Bytes_Processed(redlin,
totlen)
If len = 0 Then Exit Do
Loop
encStream.Close()
Else
RaiseEvent Callback("The key is
weak!!!!!")
End If
Catch ex As CryptographicException
RaiseEvent Callback(ex.Message)
End Try
End Sub
End Class

Thanks.
Nov 21 '05 #1
3 3183
Here's my file decryption routines, they're very similar... Take a look at
the documentation for SymmetricAlgorithm.BlockSize, I think your problem lies
here..

' <summary>
' Purpose: Decrypts a file
' </summary>
' <param name="FileToDecrypt">This is the encrypted file that will be
read from.</param>
' <param name="DecryptedFile">This is the file that will be
decrypted.</param>
Public Sub DecryptFile(ByVal strFileToDecrypt As String, _
ByVal strDecryptedFile As String)

'Create the file streams to handle the input and output files.
Dim fin As New System.IO.FileStream(strFileToDecrypt,
System.IO.FileMode.Open, System.IO.FileAccess.Read)
Dim fout As New System.IO.FileStream(strDecryptedFile,
System.IO.FileMode.OpenOrCreate, _
System.IO.FileAccess.Write)
fout.SetLength(0)

'Create variables to help with read and write.
Dim key() As Byte = GetLegalKey(strKey)
Dim bin(4096) As Byte 'This is intermediate storage for the
encryption.
Dim rdlen As Long = 8 'This is the total number of bytes written.
Dim totlen As Long = fin.Length 'Total length of the input file.
Dim len As Integer 'This is the number of bytes to be written at a
time.
Dim des As New System.Security.Cryptography.DESCryptoServiceProvi der()
Dim encStream As New System.Security.Cryptography.CryptoStream(fout, _
des.CreateDecryptor(key, key),
System.Security.Cryptography.CryptoStreamMode.Writ e)

Console.WriteLine("Encrypting...")

'Read from the input file, then encrypt and write to the output file.
While rdlen < totlen
len = fin.Read(bin, 0, 4096)
encStream.Write(bin, 0, len)
rdlen = Convert.ToInt32(rdlen + len / des.BlockSize *
des.BlockSize)
Console.WriteLine("Processed {0} bytes, {1} bytes total", len, _
rdlen)
End While

encStream.Close()
End Sub

' <summary>
' Purpose: Encrypts a file
' </summary>
' <param name="FileToEncrypt">This is the file that will be read
from.</param>
' <param name="EncryptedFile">This is the file that will be
encrypted.</param>
Public Sub EncryptFile(ByVal strFileToEncrypt As String, _
ByVal strEncryptedFile As String)

'Create the file streams to handle the input and output files.
Dim fin As New System.IO.FileStream(strFileToEncrypt,
System.IO.FileMode.Open, System.IO.FileAccess.Read)
Dim fout As New System.IO.FileStream(strEncryptedFile,
System.IO.FileMode.OpenOrCreate, _
System.IO.FileAccess.Write)
fout.SetLength(0)

'Create variables to help with read and write.
Dim key() As Byte = GetLegalKey(strKey)
Dim bin(4096) As Byte 'This is intermediate storage for the
encryption.
Dim rdlen As Long = 8 'This is the total number of bytes written.
Dim totlen As Long = fin.Length 'Total length of the input file.
Dim len As Integer 'This is the number of bytes to be written at a
time.
Dim des As New System.Security.Cryptography.DESCryptoServiceProvi der()
Dim encStream As New System.Security.Cryptography.CryptoStream(fout, _
des.CreateEncryptor(key, key),
System.Security.Cryptography.CryptoStreamMode.Writ e)

Console.WriteLine("Encrypting...")

'Read from the input file, then encrypt and write to the output file.
While rdlen < totlen
len = fin.Read(bin, 0, 4096)
encStream.Write(bin, 0, len)
rdlen = Convert.ToInt32(rdlen + len / des.BlockSize *
des.BlockSize)
Console.WriteLine("Processed {0} bytes, {1} bytes total", len, _
rdlen)
End While

encStream.Close()
fout.Close()

End Sub

"Anon" wrote:
I made this class to encrypt my DataSet before saving it
to disk. So, first in the main program I write the
DataSet to XML in a MemoryStream. I pass this stream to
the E_File sub, which encrypts the stream and writes it
out to the FileStream. Now, in the D_File function, I
read the encrypted file into a FileStream, then decrypt
it into a MemoryStream, which I pass back to my DataSet
and Read the XML into the DataSet. The problem I'm
having, is somewhere I'm losing the last 2 bytes of the
file, so if my DataSet is named "NewDataSet", the end of
the file looks like </NewDataSe
I'm not sure where these two bytes are being lost at, and
if anyone could point out my blunder, I can stop beating
my head into walls and keyboards!
Below is my code for the encryption class:

Imports System
Imports System.Text
Imports System.IO
Imports System.Security
Imports System.Security.Cryptography

Public Class Perculate
Public Event Callback(ByVal Msg As String)
Public Event Bytes_Processed(ByVal Curr As Long,
ByVal Total As Long)
Protected IV() As Byte = New Byte() {0, 0, 0, 0, 0,
0, 0, 0}

Public Function D_File(ByVal InFile As String, ByVal
key As String) As Stream
Dim fin As New FileStream(InFile, FileMode.Open,
FileAccess.Read)
Dim _ms As New MemoryStream(fin.Length)

Dim bin(100) As Byte
Dim redlin As Long = 0
Dim totlen As Long = fin.Length
Dim len As Integer

If key.Length < 24 Then key = New String("0", 24 -
key.Length) & key

Try
Dim tdes As New TripleDESCryptoServiceProvider
()
Dim decStream As New CryptoStream(_ms, _
tdes.CreateDecryptor
(Text.ASCIIEncoding.ASCII.GetBytes(key), _
IV), _
CryptoStreamMode.Write)
RaiseEvent Callback("Decrypting")

fin.Position = 0

Do
len = fin.Read(bin, 0, bin.Length)
decStream.Write(bin, 0, len)
redlin += len
RaiseEvent Bytes_Processed(redlin, totlen)
If len = 0 Then Exit Do
Loop
Return _ms
Catch ex As CryptographicException
RaiseEvent Callback(ex.Message)
End Try
End Function

Public Sub E_File(ByVal InData As Stream, ByVal
Outfile As String, ByVal Key As String)
If File.Exists(Outfile) Then File.Delete(Outfile)
Dim fout As New FileStream(Outfile,
FileMode.CreateNew, FileAccess.Write)

fout.SetLength(0)

Dim bin(100) As Byte
Dim redlin As Long = 0
Dim totlen As Long = InData.Length + 2
Dim len As Integer
Dim hByte() As Byte = ASCIIEncoding.ASCII.GetBytes
("<?xml version=" & Chr(34) & "1.0" & Chr(34) & "
standalone=" & Chr(34) & "yes" & Chr(34) & "?>" & vbCrLf)

If Key.Length > 24 Then
RaiseEvent Callback("Key must be 24 or less
characters!")
Exit Sub
ElseIf Key.Length < 6 Then
RaiseEvent Callback("Key must be 6 or more
characters!")
Exit Sub
End If
If Key.Length < 24 Then Key = New String("0", 24 -
Key.Length) & Key
Try
Dim tdes As New TripleDESCryptoServiceProvider
()
If Not tdes.IsWeakKey
(Text.ASCIIEncoding.ASCII.GetBytes(Key)) Then
Dim encStream As New CryptoStream(fout, _
tdes.CreateEncryptor
(Text.ASCIIEncoding.ASCII.GetBytes(Key), _
IV),
_
CryptoStreamMode.Write)

RaiseEvent Callback("Encrypting")

InData.Position = 0
'Force it to write out the XML header info
encStream.Write(hByte, 0, hByte.Length)
Do
len = InData.Read(bin, 0, bin.Length)
encStream.Write(bin, 0, len)
redlin += len
RaiseEvent Bytes_Processed(redlin,
totlen)
If len = 0 Then Exit Do
Loop
encStream.Close()
Else
RaiseEvent Callback("The key is
weak!!!!!")
End If
Catch ex As CryptographicException
RaiseEvent Callback(ex.Message)
End Try
End Sub
End Class

Thanks.

Nov 21 '05 #2
-----Original Message-----
Here's my file decryption routines, they're very similar... Take a look atthe documentation for SymmetricAlgorithm.BlockSize, I think your problem lieshere..

' <summary>
' Purpose: Decrypts a file
' </summary>
' <param name="FileToDecrypt">This is the encrypted file that will beread from.</param>
' <param name="DecryptedFile">This is the file that will bedecrypted.</param>
Public Sub DecryptFile(ByVal strFileToDecrypt As String, _ ByVal strDecryptedFile As String)
'Create the file streams to handle the input and output files. Dim fin As New System.IO.FileStream (strFileToDecrypt,System.IO.FileMode.Open, System.IO.FileAccess.Read)
Dim fout As New System.IO.FileStream (strDecryptedFile,System.IO.FileMode.OpenOrCreate, _
System.IO.FileAccess.Write)
fout.SetLength(0)

'Create variables to help with read and write.
Dim key() As Byte = GetLegalKey(strKey)
Dim bin(4096) As Byte 'This is intermediate storage for theencryption.
Dim rdlen As Long = 8 'This is the total number of bytes written. Dim totlen As Long = fin.Length 'Total length of the input file. Dim len As Integer 'This is the number of bytes to be written at atime.
Dim des As New System.Security.Cryptography.DESCryptoServiceProvi der() Dim encStream As New System.Security.Cryptography.CryptoStream(fout, _ des.CreateDecryptor(key, key),
System.Security.Cryptography.CryptoStreamMode.Wri te)

Console.WriteLine("Encrypting...")

'Read from the input file, then encrypt and write to the output file. While rdlen < totlen
len = fin.Read(bin, 0, 4096)
encStream.Write(bin, 0, len)
rdlen = Convert.ToInt32(rdlen + len / des.BlockSize *des.BlockSize)
Console.WriteLine("Processed {0} bytes, {1} bytes total", len, _ rdlen)
End While

encStream.Close()
End Sub

' <summary>
' Purpose: Encrypts a file
' </summary>
' <param name="FileToEncrypt">This is the file that will be readfrom.</param>
' <param name="EncryptedFile">This is the file that will beencrypted.</param>
Public Sub EncryptFile(ByVal strFileToEncrypt As String, _ ByVal strEncryptedFile As String)
'Create the file streams to handle the input and output files. Dim fin As New System.IO.FileStream (strFileToEncrypt,System.IO.FileMode.Open, System.IO.FileAccess.Read)
Dim fout As New System.IO.FileStream (strEncryptedFile,System.IO.FileMode.OpenOrCreate, _
System.IO.FileAccess.Write)
fout.SetLength(0)

'Create variables to help with read and write.
Dim key() As Byte = GetLegalKey(strKey)
Dim bin(4096) As Byte 'This is intermediate storage for theencryption.
Dim rdlen As Long = 8 'This is the total number of bytes written. Dim totlen As Long = fin.Length 'Total length of the input file. Dim len As Integer 'This is the number of bytes to be written at atime.
Dim des As New System.Security.Cryptography.DESCryptoServiceProvi der() Dim encStream As New System.Security.Cryptography.CryptoStream(fout, _ des.CreateEncryptor(key, key),
System.Security.Cryptography.CryptoStreamMode.Wri te)

Console.WriteLine("Encrypting...")

'Read from the input file, then encrypt and write to the output file. While rdlen < totlen
len = fin.Read(bin, 0, 4096)
encStream.Write(bin, 0, len)
rdlen = Convert.ToInt32(rdlen + len / des.BlockSize *des.BlockSize)
Console.WriteLine("Processed {0} bytes, {1} bytes total", len, _ rdlen)
End While

encStream.Close()
fout.Close()

End Sub

"Anon" wrote:

Thank you, I will try this tonight and post the results
in the morning.
Nov 21 '05 #3
Well, I tried Aliens suggestion, and still no luck. I do
believe I've tracked it down to the memory stream
itself. When the DataSet writes to the memory stream,
the XML header isn't written, and the last 2 bytes are
missing. My code for this is:
Dim _ms as New MemoryStream()

ds.WriteXml(_ms,XmlWriteMode.WriteSchema)

Then I pass the _ms to my encryption method. I'm gonna
look into making in in-memory XML file and seeing if I
can transfer that through. One person here at work
suggestion writing the XML to a disk file then encrypting
it, but that would defeat the purpose of encrypting the
file when someone could just copy that file out before
the program has a chance to encrypt it. I would like to
do everything in-memory.

Thanks again.
Nov 21 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Mike Peretz | last post by:
I am trying to encrypt and decrypts a dataset using ds.WriteXml and ds.ReadXml. I am able to encrypt the dataset but I can never read the data back...I get an exception of Bad Data for example,...
3
by: Varun | last post by:
How to assign a value to password field from dataset Thank yo Varun
1
by: Terry | last post by:
My Question is this, I'm having trouble getting the OleDbDataAdapter to Point to another connection string and pull the data out of the DataSet I created from the Excel Spread Sheet and Place it up...
113
by: Bonj | last post by:
I was in need of an encryption algorithm to the following requirements: 1) Must be capable of encrypting strings to a byte array, and decyrpting back again to the same string 2) Must have the same...
0
by: AndyAFCW | last post by:
I am developing my first .NET application that connects to a SQL Server 2000 database and I am having a total nightmare :x :evil: I am running Windows 2000 with Visual Studio .NET version...
2
by: Ceri | last post by:
I have been trying to display dataset data in a Crystal Report in a Crystal Reports Viewer using VB.Net. Displaying the data from the default xtreme.mdb Access database was no problem, but when...
1
by: tascien | last post by:
I want to return a dataset from my <WebMethod>. Is a dataset a common type or it's just Microsoft data type only? I want to make sure whoever connects to my service is able to understand my...
1
by: BobF | last post by:
I am working with xml files for my program's database. I want to encrypt the xml file. I want to use the Dataset.WriteXml(Stream, XmlWriteMode.WriteSchema). How can I use a cryptostream with this...
11
by: John Williams | last post by:
I've written a simple program to do XOR encryption as my first foray into understanding how encryption works. The code compiles fine, however it segmentation faults on every run. using gdb to...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.