472,954 Members | 1,846 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

File Encryption/Decryption problem

I’m trying to encrypt and decrypt a file in vb.net. I am using the
TripleDESCryptoServiceProvider encryption found in
System.Security.Cryptography. Below is the code for my Encrypt and Decrypt
functions.

While my functions read and write files the encryption/decryption is not
working properly. My test file has an original length of 66,048 bytes. My
encrypted file ends up with 66,056 bytes … 8 bytes more than my original.
When I decrypt the encrypted file the resultant file is also 66,056 bytes in
length … obviously different than the original!

I feel like I’m missing something obvious. Does anyone have any
suggestions? Thanks for your help.

Public Function EncryptFile(ByVal SourceFilename As String, ByVal
DestinationFilename As String) As Boolean

Dim fsSourceStream As System.IO.FileStream = Nothing
Dim encryptionStream As CryptoStream = Nothing
Dim fsDestinationStream As System.IO.FileStream = Nothing

Try
' Open file streams for the file reading and writing
fsSourceStream = New System.IO.FileStream(SourceFilename,
FileMode.Open, IO.FileAccess.Read)
fsDestinationStream = New
System.IO.FileStream(DestinationFilename, FileMode.Create,
IO.FileAccess.Write)

'Bytes will be encrypted by an encryption stream
encryptionStream = New CryptoStream(fsDestinationStream, _
New
TripleDESCryptoServiceProvider().CreateEncryptor(m varKey, mvarIV),
CryptoStreamMode.Write)

mvarBufferSize = 1024
' Create buffer
Dim fileBuffer(mvarBufferSize) As Byte
Dim accumulatedBytesRead As Integer = 0
Dim bytesRead As Integer

' read the file
' Process bytes from fsSourceStream through the encryptionStream
to the fsDestinationStream.
Do
bytesRead = fsSourceStream.Read(fileBuffer, 0, mvarBufferSize)
If (bytesRead = 0) Then Exit Do
encryptionStream.Write(fileBuffer, 0, bytesRead)
accumulatedBytesRead += bytesRead
Loop

encryptionStream.FlushFinalBlock()
Return True

Catch ex As Exception
MsgBox("Exception error occurred in EncryptFile." & vbNewLine &
vbNewLine _
& ex.Message, MsgBoxStyle.OkOnly Or
MsgBoxStyle.Information)
Return False

Finally

'close streams
If encryptionStream IsNot Nothing Then
encryptionStream.Close()
End If

If fsSourceStream IsNot Nothing Then
fsSourceStream.Close()
End If

If fsDestinationStream IsNot Nothing Then
fsDestinationStream.Close()
End If

End Try

End Function

Public Function DecryptFile(ByVal SourceFilename As String, ByVal
DestinationFilename As String) As Boolean

Dim fsSourceStream As System.IO.FileStream = Nothing
Dim decryptionStream As CryptoStream = Nothing
Dim fsDestinationStream As System.IO.FileStream = Nothing

Try
' Open file streams for the file reading and writing
fsSourceStream = New System.IO.FileStream(SourceFilename,
FileMode.Open, IO.FileAccess.Read)
fsDestinationStream = New
System.IO.FileStream(DestinationFilename, FileMode.Create,
IO.FileAccess.Write)

' Process bytes through a CryptoStream.
decryptionStream = New CryptoStream(fsSourceStream, _
New
TripleDESCryptoServiceProvider().CreateEncryptor(m varKey, mvarIV),
CryptoStreamMode.Read)

' Create buffer
mvarBufferSize = 1024
Dim fileBuffer(mvarBufferSize) As Byte
Dim accumulatedBytesRead As Integer = 0
Dim bytesRead As Integer

' read the file
' Process bytes from fsSourceStream to fsDestinationStream.
Do
bytesRead = decryptionStream.Read(fileBuffer, 0,
mvarBufferSize)
If (bytesRead = 0) Then Exit Do
fsDestinationStream.Write(fileBuffer, 0, bytesRead)
accumulatedBytesRead += bytesRead
Loop

fsDestinationStream.Flush()
Return True
Catch ex As Exception
MsgBox("Exception error occurred in DecryptFile." & vbNewLine &
vbNewLine _
& ex.Message, MsgBoxStyle.OkOnly Or
MsgBoxStyle.Information)
Return False

Finally

'close(streams)
If decryptionStream IsNot Nothing Then
decryptionStream.Close()
End If

If fsSourceStream IsNot Nothing Then
fsSourceStream.Close()
End If

If fsDestinationStream IsNot Nothing Then
fsDestinationStream.Close()
End If

End Try
End Function

--
Loren Baker
Jun 27 '08 #1
3 3006
DES-based encryption algorithms use an 8-byte block length. When you
encrypt a file using a DES-based function it rounds up to the next nearest
8-byte length. If you're sitting on an 8-byte boundary (like 66,048 bytes),
it is probably padding it up to the next 8-byte boundary. I would guess
that the length difference in the encrypted file is just an additional 8
bytes of padding added to the output by the encryption algorithm. In fact,
try it with a 66,041 to 66,047 byte file and I would expect the output to be
66,048 bytes in every case.

When you decrypt it's probably padding the end of the decrypted data with
NUL characters (character 0, or some other padding character). You should
be able to just strip off all character 0's from the end of the decrypted
data. If NUL characters on the end of the file might be important (for
instance if you're encrypting binary files) you might even consider adding
the file length as the first 4 or 8 bytes of the data you're encrypting so
you'll know exactly how much padding to strip off the end of the decrypted
data. There are other padding options, such as padding with a length
character to tell you exactly how many padding bytes were added to the end,
like this:

4e 5f 6a 12 9f 03 03 03

In this example the padding character is "03" indicating that the last three
bytes of the last 8-byte block are all padding characters. It's been a
while for me, but I believe you can set these padding options in the
TripleDESCryptoServiceProvider or other service providers.

"Loren" <Lo***@discussions.microsoft.comwrote in message
news:4F**********************************@microsof t.com...
I'm trying to encrypt and decrypt a file in vb.net. I am using the
TripleDESCryptoServiceProvider encryption found in
System.Security.Cryptography. Below is the code for my Encrypt and
Decrypt
functions.

While my functions read and write files the encryption/decryption is not
working properly. My test file has an original length of 66,048 bytes.
My
encrypted file ends up with 66,056 bytes . 8 bytes more than my original.
When I decrypt the encrypted file the resultant file is also 66,056 bytes
in
length . obviously different than the original!

I feel like I'm missing something obvious. Does anyone have any
suggestions? Thanks for your help.

Public Function EncryptFile(ByVal SourceFilename As String, ByVal
DestinationFilename As String) As Boolean

Dim fsSourceStream As System.IO.FileStream = Nothing
Dim encryptionStream As CryptoStream = Nothing
Dim fsDestinationStream As System.IO.FileStream = Nothing

Try
' Open file streams for the file reading and writing
fsSourceStream = New System.IO.FileStream(SourceFilename,
FileMode.Open, IO.FileAccess.Read)
fsDestinationStream = New
System.IO.FileStream(DestinationFilename, FileMode.Create,
IO.FileAccess.Write)

'Bytes will be encrypted by an encryption stream
encryptionStream = New CryptoStream(fsDestinationStream, _
New
TripleDESCryptoServiceProvider().CreateEncryptor(m varKey, mvarIV),
CryptoStreamMode.Write)

mvarBufferSize = 1024
' Create buffer
Dim fileBuffer(mvarBufferSize) As Byte
Dim accumulatedBytesRead As Integer = 0
Dim bytesRead As Integer

' read the file
' Process bytes from fsSourceStream through the
encryptionStream
to the fsDestinationStream.
Do
bytesRead = fsSourceStream.Read(fileBuffer, 0,
mvarBufferSize)
If (bytesRead = 0) Then Exit Do
encryptionStream.Write(fileBuffer, 0, bytesRead)
accumulatedBytesRead += bytesRead
Loop

encryptionStream.FlushFinalBlock()
Return True

Catch ex As Exception
MsgBox("Exception error occurred in EncryptFile." & vbNewLine &
vbNewLine _
& ex.Message, MsgBoxStyle.OkOnly Or
MsgBoxStyle.Information)
Return False

Finally

'close streams
If encryptionStream IsNot Nothing Then
encryptionStream.Close()
End If

If fsSourceStream IsNot Nothing Then
fsSourceStream.Close()
End If

If fsDestinationStream IsNot Nothing Then
fsDestinationStream.Close()
End If

End Try

End Function

Public Function DecryptFile(ByVal SourceFilename As String, ByVal
DestinationFilename As String) As Boolean

Dim fsSourceStream As System.IO.FileStream = Nothing
Dim decryptionStream As CryptoStream = Nothing
Dim fsDestinationStream As System.IO.FileStream = Nothing

Try
' Open file streams for the file reading and writing
fsSourceStream = New System.IO.FileStream(SourceFilename,
FileMode.Open, IO.FileAccess.Read)
fsDestinationStream = New
System.IO.FileStream(DestinationFilename, FileMode.Create,
IO.FileAccess.Write)

' Process bytes through a CryptoStream.
decryptionStream = New CryptoStream(fsSourceStream, _
New
TripleDESCryptoServiceProvider().CreateEncryptor(m varKey, mvarIV),
CryptoStreamMode.Read)

' Create buffer
mvarBufferSize = 1024
Dim fileBuffer(mvarBufferSize) As Byte
Dim accumulatedBytesRead As Integer = 0
Dim bytesRead As Integer

' read the file
' Process bytes from fsSourceStream to fsDestinationStream.
Do
bytesRead = decryptionStream.Read(fileBuffer, 0,
mvarBufferSize)
If (bytesRead = 0) Then Exit Do
fsDestinationStream.Write(fileBuffer, 0, bytesRead)
accumulatedBytesRead += bytesRead
Loop

fsDestinationStream.Flush()
Return True
Catch ex As Exception
MsgBox("Exception error occurred in DecryptFile." & vbNewLine &
vbNewLine _
& ex.Message, MsgBoxStyle.OkOnly Or
MsgBoxStyle.Information)
Return False

Finally

'close(streams)
If decryptionStream IsNot Nothing Then
decryptionStream.Close()
End If

If fsSourceStream IsNot Nothing Then
fsSourceStream.Close()
End If

If fsDestinationStream IsNot Nothing Then
fsDestinationStream.Close()
End If

End Try
End Function

--
Loren Baker

Jun 27 '08 #2
Thanks Mike. I think that you’re correct in DES-based encryption algorithms
use an 8-byte block length. However, my problem was far more simply
corrected (I knew I couldn’t see the forest from the trees!). My error was
in my decryption function where I create my decryptionStream. The error was
that I created and “Encryptor” instead of “Decryptor” in this function.
After making that change both functions worked correctly.

Thanks for your help.

--
Loren Baker
"Mike C#" wrote:
DES-based encryption algorithms use an 8-byte block length. When you
encrypt a file using a DES-based function it rounds up to the next nearest
8-byte length. If you're sitting on an 8-byte boundary (like 66,048 bytes),
it is probably padding it up to the next 8-byte boundary. I would guess
that the length difference in the encrypted file is just an additional 8
bytes of padding added to the output by the encryption algorithm. In fact,
try it with a 66,041 to 66,047 byte file and I would expect the output to be
66,048 bytes in every case.

When you decrypt it's probably padding the end of the decrypted data with
NUL characters (character 0, or some other padding character). You should
be able to just strip off all character 0's from the end of the decrypted
data. If NUL characters on the end of the file might be important (for
instance if you're encrypting binary files) you might even consider adding
the file length as the first 4 or 8 bytes of the data you're encrypting so
you'll know exactly how much padding to strip off the end of the decrypted
data. There are other padding options, such as padding with a length
character to tell you exactly how many padding bytes were added to the end,
like this:

4e 5f 6a 12 9f 03 03 03

In this example the padding character is "03" indicating that the last three
bytes of the last 8-byte block are all padding characters. It's been a
while for me, but I believe you can set these padding options in the
TripleDESCryptoServiceProvider or other service providers.

"Loren" <Lo***@discussions.microsoft.comwrote in message
news:4F**********************************@microsof t.com...
I'm trying to encrypt and decrypt a file in vb.net. I am using the
TripleDESCryptoServiceProvider encryption found in
System.Security.Cryptography. Below is the code for my Encrypt and
Decrypt
functions.

While my functions read and write files the encryption/decryption is not
working properly. My test file has an original length of 66,048 bytes.
My
encrypted file ends up with 66,056 bytes . 8 bytes more than my original.
When I decrypt the encrypted file the resultant file is also 66,056 bytes
in
length . obviously different than the original!

I feel like I'm missing something obvious. Does anyone have any
suggestions? Thanks for your help.

Public Function EncryptFile(ByVal SourceFilename As String, ByVal
DestinationFilename As String) As Boolean

Dim fsSourceStream As System.IO.FileStream = Nothing
Dim encryptionStream As CryptoStream = Nothing
Dim fsDestinationStream As System.IO.FileStream = Nothing

Try
' Open file streams for the file reading and writing
fsSourceStream = New System.IO.FileStream(SourceFilename,
FileMode.Open, IO.FileAccess.Read)
fsDestinationStream = New
System.IO.FileStream(DestinationFilename, FileMode.Create,
IO.FileAccess.Write)

'Bytes will be encrypted by an encryption stream
encryptionStream = New CryptoStream(fsDestinationStream, _
New
TripleDESCryptoServiceProvider().CreateEncryptor(m varKey, mvarIV),
CryptoStreamMode.Write)

mvarBufferSize = 1024
' Create buffer
Dim fileBuffer(mvarBufferSize) As Byte
Dim accumulatedBytesRead As Integer = 0
Dim bytesRead As Integer

' read the file
' Process bytes from fsSourceStream through the
encryptionStream
to the fsDestinationStream.
Do
bytesRead = fsSourceStream.Read(fileBuffer, 0,
mvarBufferSize)
If (bytesRead = 0) Then Exit Do
encryptionStream.Write(fileBuffer, 0, bytesRead)
accumulatedBytesRead += bytesRead
Loop

encryptionStream.FlushFinalBlock()
Return True

Catch ex As Exception
MsgBox("Exception error occurred in EncryptFile." & vbNewLine &
vbNewLine _
& ex.Message, MsgBoxStyle.OkOnly Or
MsgBoxStyle.Information)
Return False

Finally

'close streams
If encryptionStream IsNot Nothing Then
encryptionStream.Close()
End If

If fsSourceStream IsNot Nothing Then
fsSourceStream.Close()
End If

If fsDestinationStream IsNot Nothing Then
fsDestinationStream.Close()
End If

End Try

End Function

Public Function DecryptFile(ByVal SourceFilename As String, ByVal
DestinationFilename As String) As Boolean

Dim fsSourceStream As System.IO.FileStream = Nothing
Dim decryptionStream As CryptoStream = Nothing
Dim fsDestinationStream As System.IO.FileStream = Nothing

Try
' Open file streams for the file reading and writing
fsSourceStream = New System.IO.FileStream(SourceFilename,
FileMode.Open, IO.FileAccess.Read)
fsDestinationStream = New
System.IO.FileStream(DestinationFilename, FileMode.Create,
IO.FileAccess.Write)

' Process bytes through a CryptoStream.
decryptionStream = New CryptoStream(fsSourceStream, _
New
TripleDESCryptoServiceProvider().CreateEncryptor(m varKey, mvarIV),
CryptoStreamMode.Read)

' Create buffer
mvarBufferSize = 1024
Dim fileBuffer(mvarBufferSize) As Byte
Dim accumulatedBytesRead As Integer = 0
Dim bytesRead As Integer

' read the file
' Process bytes from fsSourceStream to fsDestinationStream.
Do
bytesRead = decryptionStream.Read(fileBuffer, 0,
mvarBufferSize)
If (bytesRead = 0) Then Exit Do
fsDestinationStream.Write(fileBuffer, 0, bytesRead)
accumulatedBytesRead += bytesRead
Loop

fsDestinationStream.Flush()
Return True
Catch ex As Exception
MsgBox("Exception error occurred in DecryptFile." & vbNewLine &
vbNewLine _
& ex.Message, MsgBoxStyle.OkOnly Or
MsgBoxStyle.Information)
Return False

Finally

'close(streams)
If decryptionStream IsNot Nothing Then
decryptionStream.Close()
End If

If fsSourceStream IsNot Nothing Then
fsSourceStream.Close()
End If

If fsDestinationStream IsNot Nothing Then
fsDestinationStream.Close()
End If

End Try
End Function

--
Loren Baker


Jun 27 '08 #3

"Loren" <Lo***@discussions.microsoft.comwrote in message
news:12**********************************@microsof t.com...
Thanks Mike. I think that you're correct in DES-based encryption
algorithms
use an 8-byte block length. However, my problem was far more simply
corrected (I knew I couldn't see the forest from the trees!). My error
was
in my decryption function where I create my decryptionStream. The error
was
that I created and "Encryptor" instead of "Decryptor" in this function.
After making that change both functions worked correctly.

Thanks for your help.

--
Loren Baker.
Very cool, so I guess the decryption service provider automatically strips
the extra padding when you decrypt it. Thanks.
Jun 27 '08 #4

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

Similar topics

1
by: D. Alvarado | last post by:
On my Fedora Core 2 Linux dev box, I have installed mcrypt and compiled PHP with the --with-mcrypt option. I am concerned that when I move to another hosting enviornment mcrypt will not be...
1
by: Jase H | last post by:
Hello, I have a ASP.NET web application problem involving the data encryption and decryption assembly(DLL) used on the connection string value that is set in the webconfig file. The problem...
5
by: Robert Bull | last post by:
I am looking for an example of encryption/decryption in asp.net. I want to encrypt a string before I send it to a Web Service, decrypt it on the Web Service then encrypt the results on the Web...
2
by: almurph | last post by:
Hi everyone, Can you help me please? I am having a problem with the encryption/decryption of words with the Irish fada in them. The Irish fada is like this: /. It's kind of like the...
2
by: tfoxusenet | last post by:
Hi, I need to encrypt/decrypt some data for my C# application that can also be read on a unix system, and need a quick, simple, cross-platform solution I can embed in my own code that doesn't...
3
by: Mythran | last post by:
I have googled and tested and tried and still I can't seem to implement a simple encryption/decryption console application. My goal is to create two methods. public byte Encrypt(string...
1
by: PatCPA | last post by:
Can someone help me with this? I'm new to C++. Here's my problem. I am to prompt the user to either 'e' encrypt or 'd' decrypt a 4-digit number. Each 4 digit number is to be replaced by the sum...
1
by: ppuniversal | last post by:
Hello, I am making a DES encryption/decryption program using OpenSSL library. I am using function des_ecb_encrypt(des_cblock *input, des_cblock *output, des_cblock *keysched, int mode); ...
0
by: Dipanwita | last post by:
I have written a RSA encryption/decryption function in c using the formula a = b^c %n. For solving the equation I have used Squaring and multiplying method for modulo exponentiation . These...
0
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 4 Oct 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
by: Aliciasmith | last post by:
In an age dominated by smartphones, having a mobile app for your business is no longer an option; it's a necessity. Whether you're a startup or an established enterprise, finding the right mobile app...
0
tracyyun
by: tracyyun | last post by:
Hello everyone, I have a question and would like some advice on network connectivity. I have one computer connected to my router via WiFi, but I have two other computers that I want to be able to...
3
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be using a very simple database which has Form (clsForm) & Report (clsReport) classes that simply handle making the calling Form invisible until the Form, or all...
1
by: Teri B | last post by:
Hi, I have created a sub-form Roles. In my course form the user selects the roles assigned to the course. 0ne-to-many. One course many roles. Then I created a report based on the Course form and...
0
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be focusing on the Report (clsReport) class. This simply handles making the calling Form invisible until all of the Reports opened by it have been closed, when it...
0
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...

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.