Click here to Skip to main content
15,909,896 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi i'm trying to make a file encrypter with RC2. I don't know what the problem is but when I encrypt a file I get no error messages but when the output file comes out it's blank! zero bytes!

What am I doing wrong?



VB
#Region "1. Global Variables "
     '*************************
    '** Global Variables
    '*************************

    Dim strFileToEncrypt As String
    Dim strFileToDecrypt As String
    Dim strOutputEncrypt As String
    Dim strOutputDecrypt As String
    Dim fsInput As System.IO.FileStream
    Dim fsOutput As System.IO.FileStream

#End Region


#Region "2. Create A Key "
     '*************************
    '** Create A Key
    '*************************

    Private Function CreateKey(ByVal Password As String) As Byte()
        'Convert strPassword to an array and store in chrData.
        Dim chrData() As Char = Password.ToCharArray
        'Use intLength to get strPassword size.
        Dim intLength As Integer = chrData.GetUpperBound(0)
        'Declare bytDataToHash and make it the same size as chrData.
        Dim bytDataToHash(intLength) As Byte

        'Use For Next to convert and store chrData into bytDataToHash.
        For i As Integer = 0 To chrData.GetUpperBound(0)
            bytDataToHash(i) = CByte(Asc(chrData(i)))
        Next

        'Declare what hash to use.
        Dim SHA512 As New System.Security.Cryptography.SHA512Managed
        'Declare bytResult, Hash bytDataToHash and store it in bytResult.
        Dim bytResult As Byte() = SHA512.ComputeHash(bytDataToHash)
        'Declare bytKey(31).  It will hold 256 bits.
        Dim bytKey(31) As Byte

        'Use For Next to put a specific size (256 bits) of 
        'bytResult into bytKey. The 0 To 31 will put the first 256 bits
        'of 512 bits into bytKey.
        For i As Integer = 0 To 31
            bytKey(i) = bytResult(i)
        Next

        Return bytKey 'Return the key.
    End Function

#End Region


#Region "3. Create An IV "
     '*************************
    '** Create An IV
    '*************************

    Private Function CreateIV(ByVal Password As String) As Byte()
        'Convert strPassword to an array and store in chrData.
        Dim chrData() As Char = Password.ToCharArray
        'Use intLength to get strPassword size.
        Dim intLength As Integer = chrData.GetUpperBound(0)
        'Declare bytDataToHash and make it the same size as chrData.
        Dim bytDataToHash(intLength) As Byte

        'Use For Next to convert and store chrData into bytDataToHash.
        For i As Integer = 0 To chrData.GetUpperBound(0)
            bytDataToHash(i) = CByte(Asc(chrData(i)))
        Next

        'Declare what hash to use.
        Dim SHA512 As New System.Security.Cryptography.SHA512Managed
        'Declare bytResult, Hash bytDataToHash and store it in bytResult.
        Dim bytResult As Byte() = SHA512.ComputeHash(bytDataToHash)
        'Declare bytIV(15).  It will hold 128 bits.
        Dim bytIV(15) As Byte

        'Use For Next to put a specific size (128 bits) of 
        'bytResult into bytIV. The 0 To 30 for bytKey used the first 256 bits.
        'of the hashed password. The 32 To 47 will put the next 128 bits into bytIV.
        For i As Integer = 32 To 47
            bytIV(i - 32) = bytResult(i)
        Next

        Return bytIV 'return the IV
    End Function

#End Region


#Region "4. Encrypt / Decrypt File "
     Public Sub DecryptFile(ByVal InputFile As String, ByVal OutputFile As String, ByVal Password As string, Optional ByVal DeleteUnencryptedFile As Boolean = False)
        Try 'In case of errors.

            'Setup file streams to handle input and output.
            fsInput = New System.IO.FileStream(InputFile, FileMode.Open, _
                                               FileAccess.Read)
            fsOutput = New System.IO.FileStream(OutputFile, FileMode.OpenOrCreate, _
                                                FileAccess.Write)
            fsOutput.SetLength(0) 'make sure fsOutput is empty

            'Declare variables for encrypt/decrypt process.
            Dim bytBuffer(4096) As Byte 'holds a block of bytes for processing
            Dim lngBytesProcessed As Long = 0 'running count of bytes processed
            Dim lngFileLength As Long = fsInput.Length 'the input file's length
            Dim intBytesInCurrentBlock As Integer 'current bytes being processed
            Dim csCryptoStream As CryptoStream
            'Declare your CryptoServiceProvider.
            Dim Rijndael As New System.Security.Cryptography.RC2CryptoServiceProvider

            csCryptoStream = New CryptoStream(fsOutput, _
            Rijndael.CreateDecryptor(createkey(Password), createIV(password), _
            CryptoStreamMode.Write)

            'Use While to loop until all of the file is processed.
            While lngBytesProcessed < lngFileLength
                'Read file with the input filestream.
                intBytesInCurrentBlock = fsInput.Read(bytBuffer, 0, 4096)
                'Write output file with the cryptostream.
                csCryptoStream.Write(bytBuffer, 0, intBytesInCurrentBlock)
                'Update lngBytesProcessed
                lngBytesProcessed = lngBytesProcessed + CLng(intBytesInCurrentBlock)
                'Update Progress Bar
            End While

            'Close FileStreams and CryptoStream.
            csCryptoStream.Close()
            fsInput.Close()
            fsOutput.Close()


            If DeleteUnencryptedFile = True Then
                'If decrypting then delete the encrypted file.
                Dim fileEncrypted As New FileInfo(InputFile)
                fileEncrypted.Delete()
            End If
            'Update the user when the file is done.
            Dim Wrap As String = Chr(13) + Chr(10)



            'Catch file not found error.
        Catch When Err.Number = 53 'if file not found
            MsgBox("Please check to make sure the path and filename" + _
                    "are correct and if the file exists.", _
                     MsgBoxStyle.Exclamation, "Invalid Path or Filename")

            'Catch all other errors. And delete partial files.
        Catch
            fsInput.Close()
            fsOutput.Close()

            Dim fileDelete As New FileInfo(OutputFile)
            fileDelete.Delete()

            MsgBox("Please check to make sure that you entered the correct " + _
                    "password.", MsgBoxStyle.Critical, "Invalid Password")

        End Try
    End Sub

    Public Sub EncryptFile(ByVal InputFile As String, _
                                         ByVal OutputFile As String, _
                                     ByVal Password As string , Optional ByVal DeleteEncryptedFile As Boolean = False)
        Try 'In case of errors.

            'Setup file streams to handle input and output.
            fsInput = New System.IO.FileStream(InputFile, FileMode.Open, _
                                               FileAccess.Read)
            fsOutput = New System.IO.FileStream(OutputFile, FileMode.OpenOrCreate, _
                                                FileAccess.Write)
            fsOutput.SetLength(0) 'make sure fsOutput is empty

            'Declare variables for encrypt/decrypt process.
            Dim bytBuffer(4096) As Byte 'holds a block of bytes for processing
            Dim lngBytesProcessed As Long = 0 'running count of bytes processed
            Dim lngFileLength As Long = fsInput.Length 'the input file's length
            Dim intBytesInCurrentBlock As Integer 'current bytes being processed
            Dim csCryptoStream As CryptoStream
            'Declare your CryptoServiceProvider.
            Dim Rijndael As New System.Security.Cryptography.RC2CryptoServiceProvider

            csCryptoStream = New CryptoStream(fsOutput, _
            Rijndael.CreateEncryptorcreatekey(Password), createIV(password)), _
            CryptoStreamMode.Write)



            'Use While to loop until all of the file is processed.
            While lngBytesProcessed < lngFileLength
                'Read file with the input filestream.
                intBytesInCurrentBlock = fsInput.Read(bytBuffer, 0, 4096)
                'Write output file with the cryptostream.
                csCryptoStream.Write(bytBuffer, 0, intBytesInCurrentBlock)
                'Update lngBytesProcessed
                lngBytesProcessed = lngBytesProcessed + CLng(intBytesInCurrentBlock)
                'Update Progress Bar
            End While

            'Close FileStreams and CryptoStream.
            csCryptoStream.Close()
            fsInput.Close()
            fsOutput.Close()

            'If encrypting then delete the original unencrypted file.
            If DeleteEncryptedFile = True Then
                Dim fileOriginal As New FileInfo(InputFile)
                fileOriginal.Delete()
            End If

            'Update the user when the file is done.
            Dim Wrap As String = Chr(13) + Chr(10)

            'Catch file not found error.
        Catch When Err.Number = 53 'if file not found
            MsgBox("Please check to make sure the path and filename" + _
                    "are correct and if the file exists.", _
                     MsgBoxStyle.Exclamation, "Invalid Path or Filename")

            'Catch all other errors. And delete partial files.
        Catch
            fsInput.Close()
            fsOutput.Close()

        End Try
    End Sub

#End Region


[Modified: just moved it down so it wasn't constrained by the voting box]
Posted
Updated 21-Jun-10 7:18am
v3
Comments
TheyCallMeMrJames 21-Jun-10 8:59am    
What is the length of your original file? If you set a break point after the while loop, what is the length of your encrypted stream? Have you read through the article this code came from to better understand what's going on?
http://www.codeproject.com/KB/security/EncryptFile.aspx
William Winner 21-Jun-10 15:27pm    
what code do you want me to provide that wasn't provided with the article? I copied and pasted the code from the article, and then called the methods. So if you want code, go to the original.

found another typo...at least I hope it's a typo:

VB
'If encrypting then delete the original unencrypted file.
If DeleteEncryptedFile = True Then

within the encrypt method.

Aside from the two typos, the code you posted is fine, so the only problem would be with what you were passing into the methods.
 
Share this answer
 
Comments
Code Master38 28-Jun-10 1:23am    
Reason for my vote of 5
AWESOME!
This is a basic question, but did you step through the code?

And, I hope it's a typing error when transferring the code into here but
VB
Rijndael.CreateEncryptorcreatekey(Password), createIV(password))

won't work because you're missing a ( after CreateEncryptor.

And a hint...but since you're not using a Rijndael code, you should change the name of the object to something that actually identifies it as an RC2.

Step through and see if the csCryptoStream is created correctly. Since the creation of it is the only place that you've actually changed the code from the CP article, I would look there first. I know that the rest of the code works with Rijndael because I use it in a program.
 
Share this answer
 
Comments
Code Master38 21-Jun-10 14:06pm    
Rijndael.CreateEncryptorcreatekey(Password), createIV(password)) was a typo and yes I stepped through the code. And could you be more specific? Like with some code?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900