1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Help needed with cryptography!

Discussion in 'Visual Basic .NET' started by tb303, Jun 15, 2012.

  1. tb303

    tb303 Power Member

    Joined:
    Dec 18, 2011
    Messages:
    601
    Likes Received:
    280
    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??