Help needed with cryptography!

tb303

Supreme Member
Joined
Dec 18, 2011
Messages
1,237
Reaction score
909
Hi ive been trying to use System.Security.Cryptography to encrypt and decrypt a file but its not working for me

this code
Code:
    Private Sub EncryptFile(ByVal sInputFilename As String, ByVal sOutputFilename As String, ByVal sKey As String)
        Dim fsInput As New FileStream(sInputFilename, FileMode.Open, FileAccess.Read)
        Dim fsEncrypted As New FileStream(sOutputFilename, FileMode.Create, FileAccess.Write)
        Dim DES As New DESCryptoServiceProvider()
        DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey)
        DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey)
        Dim desencrypt As ICryptoTransform = DES.CreateEncryptor()
        Dim cryptostream As New CryptoStream(fsEncrypted, desencrypt, CryptoStreamMode.Write)
        Dim bytearrayinput(fsInput.Length - 1) As Byte
        fsInput.Read(bytearrayinput, 0, bytearrayinput.Length)
        cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length)
        cryptostream.Close()
    End Sub

called with
Code:
EncryptFile(OpenFileDialog1.FileName, SaveFileDialog1.FileName, "12345678")

seems to work ok and i get a file the same size as the source file

heres where it goes wrong though

this code
Code:
    Private Sub DecryptFile(ByVal sInputFilename As String, ByVal sOutputFilename As String, ByVal sKey As String)
        Dim DES As New DESCryptoServiceProvider()
        DES.Key() = ASCIIEncoding.ASCII.GetBytes(sKey)
        DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey)
        Dim fsread As New FileStream(sInputFilename, FileMode.Open, FileAccess.Read)
        Dim desdecrypt As ICryptoTransform = DES.CreateDecryptor()
        Dim cryptostreamDecr As New CryptoStream(fsread, desdecrypt, CryptoStreamMode.Read)
        Dim fsDecrypted As New StreamWriter(sOutputFilename)
        fsDecrypted.Write(New StreamReader(cryptostreamDecr).ReadToEnd)
        fsDecrypted.Flush()
        fsDecrypted.Close()
    End Sub

called with
Code:
DecryptFile(OpenFileDialog1.FileName, SaveFileDialog1.FileName, "12345678")

outputs a file that is almost 2x as large as the source file that was encrypted.

whats going on im sure this was working fine a few weeks ago and i cant see anything obviously wrong with it.

anyone help me out??
 
Back
Top