473,657 Members | 2,492 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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(InFi le, FileMode.Open,
FileAccess.Read )
Dim _ms As New MemoryStream(fi n.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 TripleDESCrypto ServiceProvider
()
Dim decStream As New CryptoStream(_m s, _
tdes.CreateDecr yptor
(Text.ASCIIEnco ding.ASCII.GetB ytes(key), _
IV), _
CryptoStreamMod e.Write)
RaiseEvent Callback("Decry pting")

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 CryptographicEx ception
RaiseEvent Callback(ex.Mes sage)
End Try
End Function

Public Sub E_File(ByVal InData As Stream, ByVal
Outfile As String, ByVal Key As String)
If File.Exists(Out file) Then File.Delete(Out file)
Dim fout As New FileStream(Outf ile,
FileMode.Create New, FileAccess.Writ e)

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.A SCII.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 TripleDESCrypto ServiceProvider
()
If Not tdes.IsWeakKey
(Text.ASCIIEnco ding.ASCII.GetB ytes(Key)) Then
Dim encStream As New CryptoStream(fo ut, _
tdes.CreateEncr yptor
(Text.ASCIIEnco ding.ASCII.GetB ytes(Key), _
IV),
_
CryptoStreamMod e.Write)

RaiseEvent Callback("Encry pting")

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 CryptographicEx ception
RaiseEvent Callback(ex.Mes sage)
End Try
End Sub
End Class

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

' <summary>
' Purpose: Decrypts a file
' </summary>
' <param name="FileToDec rypt">This is the encrypted file that will be
read from.</param>
' <param name="Decrypted File">This is the file that will be
decrypted.</param>
Public Sub DecryptFile(ByV al strFileToDecryp t As String, _
ByVal strDecryptedFil e As String)

'Create the file streams to handle the input and output files.
Dim fin As New System.IO.FileS tream(strFileTo Decrypt,
System.IO.FileM ode.Open, System.IO.FileA ccess.Read)
Dim fout As New System.IO.FileS tream(strDecryp tedFile,
System.IO.FileM ode.OpenOrCreat e, _
System.IO.FileA ccess.Write)
fout.SetLength( 0)

'Create variables to help with read and write.
Dim key() As Byte = GetLegalKey(str Key)
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.D ESCryptoService Provider()
Dim encStream As New System.Security .Cryptography.C ryptoStream(fou t, _
des.CreateDecry ptor(key, key),
System.Security .Cryptography.C ryptoStreamMode .Write)

Console.WriteLi ne("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.WriteLi ne("Processed {0} bytes, {1} bytes total", len, _
rdlen)
End While

encStream.Close ()
End Sub

' <summary>
' Purpose: Encrypts a file
' </summary>
' <param name="FileToEnc rypt">This is the file that will be read
from.</param>
' <param name="Encrypted File">This is the file that will be
encrypted.</param>
Public Sub EncryptFile(ByV al strFileToEncryp t As String, _
ByVal strEncryptedFil e As String)

'Create the file streams to handle the input and output files.
Dim fin As New System.IO.FileS tream(strFileTo Encrypt,
System.IO.FileM ode.Open, System.IO.FileA ccess.Read)
Dim fout As New System.IO.FileS tream(strEncryp tedFile,
System.IO.FileM ode.OpenOrCreat e, _
System.IO.FileA ccess.Write)
fout.SetLength( 0)

'Create variables to help with read and write.
Dim key() As Byte = GetLegalKey(str Key)
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.D ESCryptoService Provider()
Dim encStream As New System.Security .Cryptography.C ryptoStream(fou t, _
des.CreateEncry ptor(key, key),
System.Security .Cryptography.C ryptoStreamMode .Write)

Console.WriteLi ne("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.WriteLi ne("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(InFi le, FileMode.Open,
FileAccess.Read )
Dim _ms As New MemoryStream(fi n.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 TripleDESCrypto ServiceProvider
()
Dim decStream As New CryptoStream(_m s, _
tdes.CreateDecr yptor
(Text.ASCIIEnco ding.ASCII.GetB ytes(key), _
IV), _
CryptoStreamMod e.Write)
RaiseEvent Callback("Decry pting")

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 CryptographicEx ception
RaiseEvent Callback(ex.Mes sage)
End Try
End Function

Public Sub E_File(ByVal InData As Stream, ByVal
Outfile As String, ByVal Key As String)
If File.Exists(Out file) Then File.Delete(Out file)
Dim fout As New FileStream(Outf ile,
FileMode.Create New, FileAccess.Writ e)

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.A SCII.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 TripleDESCrypto ServiceProvider
()
If Not tdes.IsWeakKey
(Text.ASCIIEnco ding.ASCII.GetB ytes(Key)) Then
Dim encStream As New CryptoStream(fo ut, _
tdes.CreateEncr yptor
(Text.ASCIIEnco ding.ASCII.GetB ytes(Key), _
IV),
_
CryptoStreamMod e.Write)

RaiseEvent Callback("Encry pting")

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 CryptographicEx ception
RaiseEvent Callback(ex.Mes sage)
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 SymmetricAlgori thm.BlockSize, I think your problem lieshere..

' <summary>
' Purpose: Decrypts a file
' </summary>
' <param name="FileToDec rypt">This is the encrypted file that will beread from.</param>
' <param name="Decrypted File">This is the file that will bedecrypted.</param>
Public Sub DecryptFile(ByV al strFileToDecryp t As String, _ ByVal strDecryptedFil e As String)
'Create the file streams to handle the input and output files. Dim fin As New System.IO.FileS tream (strFileToDecry pt,System.IO.File Mode.Open, System.IO.FileA ccess.Read)
Dim fout As New System.IO.FileS tream (strDecryptedFi le,System.IO.File Mode.OpenOrCrea te, _
System.IO.FileA ccess.Write)
fout.SetLength( 0)

'Create variables to help with read and write.
Dim key() As Byte = GetLegalKey(str Key)
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.D ESCryptoService Provider() Dim encStream As New System.Security .Cryptography.C ryptoStream(fou t, _ des.CreateDecry ptor(key, key),
System.Securit y.Cryptography. CryptoStreamMod e.Write)

Console.WriteLi ne("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.BlockSiz e)
Console.WriteLi ne("Processed {0} bytes, {1} bytes total", len, _ rdlen)
End While

encStream.Close ()
End Sub

' <summary>
' Purpose: Encrypts a file
' </summary>
' <param name="FileToEnc rypt">This is the file that will be readfrom.</param>
' <param name="Encrypted File">This is the file that will beencrypted.</param>
Public Sub EncryptFile(ByV al strFileToEncryp t As String, _ ByVal strEncryptedFil e As String)
'Create the file streams to handle the input and output files. Dim fin As New System.IO.FileS tream (strFileToEncry pt,System.IO.File Mode.Open, System.IO.FileA ccess.Read)
Dim fout As New System.IO.FileS tream (strEncryptedFi le,System.IO.File Mode.OpenOrCrea te, _
System.IO.FileA ccess.Write)
fout.SetLength( 0)

'Create variables to help with read and write.
Dim key() As Byte = GetLegalKey(str Key)
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.D ESCryptoService Provider() Dim encStream As New System.Security .Cryptography.C ryptoStream(fou t, _ des.CreateEncry ptor(key, key),
System.Securit y.Cryptography. CryptoStreamMod e.Write)

Console.WriteLi ne("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.BlockSiz e)
Console.WriteLi ne("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.W riteSchema)

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
2433
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, for writing there seems to be no problem... using (IsolatedStorageFileStream storeStream = new IsolatedStorageFileStream("reg.xml", FileMode.Create, FileAccess.ReadWrite,
3
2307
by: Varun | last post by:
How to assign a value to password field from dataset Thank yo Varun
1
382
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 in a SQL table. I'm Sorry for the mess of Code but I've been at this all Day now. If you have any Ideas I could surely use the help. Thank You, Terry string File = ofdExcel.FileName; string sConn = @"Provider=Microsoft.Jet.OLEDB.4.0;" + "Data...
113
12298
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 algorithm work with strings that may or may not be unicode 3) Number of bytes back must either be <= number of _TCHARs in * sizeof(_TCHAR), or the relation between output size and input size can be calculated simply. Has to take into account the...
0
1149
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 7.0.9466, .NET Framework 1.0.3705 and SQL Server 2000. I have created a simple table in an SQL database. SQL server includes ASPNET as a valid login which has unlimited access to all databases, including the database I have created. The ASPNET...
2
2825
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 trying to display data from an SQL 2000 database, no data ever shows. Could somebody please tell me what alterations need to be made to the following code? Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles...
1
1328
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 webservice... being Java, php, etc... Tascien
1
2381
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 to write an encrypted file to disk? The Stream parameter for WriteXML is limited to an IO stream which does not include cryptostream. I guess I'm having conceptual difficulty understanding how to get the data into a stream and how crypto and file...
11
5030
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 debug it let me narrow the problem down to the Cipher function I think it faults at line 84 or 85. The program makes it's first read/cipher/write pass without issue but the second pass kills it. Using gdb to print the variables left showed me the...
0
8403
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8737
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
7345
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6174
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5636
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4168
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4327
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2735
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1730
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.