We help IT Professionals succeed at work.
Get Started

Decryption results in Bad Data

471 Views
Last Modified: 2012-05-10
Hi Guys,

I need some help here.

I have a routine/code which encrypts a file based on a key and decrypts the file using the same key. Now I have had this routine for quite sometime now and it has worked flawlessly so far. Today while trying to decrypt a file an error occured. The file is similar to the other files I encrypt. Somehow I am unable to decrypt a particular file no matter what.

I am attaching two similar files, one which encrypts & decrypts fine and the other which encrypts ok but does not decrypt properly. I am stunned to be honest.

CODE : ENCRYPT

'create an 8-byte long array to hold the key 
    Private TheKey(7) As Byte ' it was public earlier
    'Stuff some random values into the vector: 
    Private Vector() As Byte = {&H12, &H44, &H16, &HEE, &H88, &H15, &HDD, &H41}

    Friend Sub Encrypt(ByVal inName As String, ByVal outName As String, ByVal key As String)
        Try
            CreateKey(key)
            Dim storage(4096) As Byte   'create buffer 
            Dim totalBytesWritten As Long = 8  'Keeps track of bytes written. 

            Dim packageSize As Integer   'Specifies the number of bytes written at one time. 

            'Declare the file streams. 
            Dim fin As New FileStream(inName, FileMode.Open, FileAccess.Read)
            Dim fout As New FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write)
            fout.SetLength(0)

            Dim totalFileLength As Long = fin.Length  'Specifies the size of the source file. 

            'create the Crypto object 
            Dim des As New DESCryptoServiceProvider()

            Dim crStream As New CryptoStream(fout, des.CreateEncryptor(TheKey, Vector), CryptoStreamMode.Write)

            'flow the streams 
            While totalBytesWritten < totalFileLength
                packageSize = fin.Read(storage, 0, 4096)
                crStream.Write(storage, 0, packageSize)
                totalBytesWritten = Convert.ToInt32(totalBytesWritten + packageSize / des.BlockSize * des.BlockSize)
            End While

            crStream.Close()
            fin.Close()
            fout.Close()
        Catch e As Exception
            MsgBox(e.Message, MsgBoxStyle.Critical)
        End Try

    End Sub

Open in new window


CODE: DECRYPT

Friend Sub Decrypt(ByVal inName As String, ByVal outName As String, ByVal key As String, ByRef IsErr As Boolean)
        CreateKey(key)
        Dim storage(4096) As Byte
        Dim totalBytesWritten As Long = 8
        Dim packageSize As Integer
        Dim fin As New FileStream(inName, FileMode.Open, FileAccess.Read)
        Dim fout As New FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write)
        fout.SetLength(0)
        Dim totalFileLength As Long = fin.Length
        Dim des As New DESCryptoServiceProvider()
        Dim crStream As New CryptoStream(fout, des.CreateDecryptor(TheKey, Vector), CryptoStreamMode.Write)

        Try
            While totalBytesWritten < totalFileLength
                packageSize = fin.Read(storage, 0, 4096)
                crStream.Write(storage, 0, packageSize)
                totalBytesWritten = Convert.ToInt32(totalBytesWritten + packageSize / des.BlockSize * des.BlockSize)
              End While
             
            crStream.FlushFinalBlock()  ' added lately  
            crStream.Close()
            fin.Close()
            fout.Close()
        Catch e As Exception
            IsErr = True
            fin.Close()
            fout.Close()
        End Try

    End Sub

Open in new window


COMMON FUNCTION CODE:

Private Sub CreateKey(ByVal strKey As String)

        ' Byte array to hold key 
        Dim arrByte(7) As Byte

        Dim AscEncod As New System.Text.ASCIIEncoding()
        Dim i As Integer = 0
        AscEncod.GetBytes(strKey, i, strKey.Length, arrByte, i)

        'Get the hash value of the password 
        Dim hashSha As New SHA1CryptoServiceProvider()
        Dim arrHash() As Byte = hashSha.ComputeHash(arrByte)

        'put the hash value into the key 
        For i = 0 To 7
            TheKey(i) = arrHash(i)
        Next i

    End Sub

Open in new window


You can call the functions to encrypt & decrypt a file like this:

 Call Encrypt("C:\fileOk.txt", "C:\FileOkEnc.dat", "key")
 Call Decrypt("C:\FileOKEnc.dat", "C:\fileOKdec.txt", "key", IsErr)

Open in new window


Try to encrypt and decrypt two very similar files. One is okay and in second one an error occurs while decrypting. I am unable to figure out why. This code has works well so far.

I did add flushfinalblock() after reading about it on the web but it didnt help either.

FileOK.txt & FileProblem.txt have been attached.

Thanks a lot,

Cheers,
Saurabh
FileOK.txt
FileProblem.txt
Comment
Watch Question
Commented:
This problem has been solved!
Unlock 1 Answer and 5 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE