Home Articles VB.Net Articles How to encrypt string or file using TripleDES

How to encrypt string or file using TripleDES

In this VB.Net Tutorial/Code Example I'm going to show you how to encrypt a string or a file using TripleDES. To see how to use this class then go to the end of this article where there is an example.

Imports System.Security.Cryptography
Imports System.IO
Imports System.Text

Namespace Security.Encryption
    Public Class SymmetricEncryption
        Public TheKey(23) As Byte
        Private Vector() As Byte = {&H12, &H44, &H16, &HEE, &H88, &H15, &HDD, &H41}

        Public Sub New(ByVal password As String)
            If password.Length <= 16 Then
                password = password & "<~{},.#'/',(%(|\'"
            ElseIf password.Length <= 24 Then
                password = password & "|`¬{:~\^(£["
                password = password.Substring(0, 24)
            Else
                password = password.Substring(0, 24)
            End If
            CreateKey(password)
        End Sub
        Private Sub CreateKey(ByVal strKey As String)

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

            Dim AscEncod As New 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 SHA256Managed
            Dim arrHash() As Byte = hashSha.ComputeHash(arrByte)

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

        End Sub

        Public Function encryptString(ByVal Input As String) As String
            Dim buffer() As Byte = Encoding.UTF8.GetBytes(Input)
            Dim des As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider
            des.Key = TheKey
            des.IV = Vector
            Return Convert.ToBase64String(des.CreateEncryptor().TransformFinalBlock(buffer, 0, buffer.Length()))
        End Function
        Public Function decryptString(ByVal Input As String) As String
            Dim buffer() As Byte = Convert.FromBase64String(Input)
            Dim des As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider
            des.Key = TheKey
            des.IV = Vector
            Return Encoding.UTF8.GetString(des.CreateDecryptor().TransformFinalBlock(buffer, 0, buffer.Length()))
        End Function
        Public Function encryptFile(ByVal inFile As String, ByVal outFile As String) As Boolean
            Dim fin As New FileStream(inFile, FileMode.Open, FileAccess.Read)
            Dim fout As New FileStream(outFile, FileMode.Create, FileAccess.Write)
            Dim tes As New TripleDESCryptoServiceProvider
            Dim rtn As Boolean = True

            rtn = performOnFile(fin, fout, tes.CreateEncryptor(TheKey, Vector))

            Return rtn
        End Function
        Public Function decryptFile(ByVal inFile As String, ByVal outFile As String) As Boolean
            Dim fin As New FileStream(inFile, FileMode.Open, FileAccess.Read)
            Dim fout As New FileStream(outFile, FileMode.Create, FileAccess.Write)
            Dim tes As New TripleDESCryptoServiceProvider
            Dim rtn As Boolean = True

            rtn = performOnFile(fin, fout, tes.CreateDecryptor(TheKey, Vector))

            Return rtn
        End Function
        Private Function performOnFile(ByVal fin As FileStream, ByVal fout As FileStream, ByVal transformer As ICryptoTransform) As Boolean
            Dim rtn As Boolean = True
            Dim storage(4096) As Byte
            Dim readLen As Integer
            Dim totalBytesWritten As Long = 8
            Dim tes As New TripleDESCryptoServiceProvider

            Try
                fout.SetLength(0)
                Dim crstream As New CryptoStream(fout, transformer, CryptoStreamMode.Write)

                While totalBytesWritten < fin.Length
                    readLen = fin.Read(storage, 0, 4096)
                    crstream.Write(storage, 0, readLen)
                    totalBytesWritten = CInt((totalBytesWritten + readLen) / tes.BlockSize * tes.BlockSize)
                End While

                crstream.Close()
                fin.Close()
            Catch ex As Exception
                rtn = False
            End Try

            Return rtn
        End Function
    End Class
End Namespace

Usage:

    Private Sub Button12_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button12.Click
        Dim enc As New SymmetricEncryption("A nice long password")
        enc.encryptFile("C:\test.txt", "C:\test.txt.enc")
        enc.decryptFile("C:\test.txt.enc", "C:\test1.txt")

        Dim tmp As String = enc.EncryptString("Hello world")
        If "Hello world" = enc.DecryptString(tmp) Then
            MsgBox("Yay")
        Else
            MsgBox("Boo")
        End If
    End Sub

Last Updated (Monday, 13 September 2010 14:32)