Write An Encrypted Text File In Visual Basic

There are many ways to encrypt text or data. In this tutorial, DESCryptoServiceProvider class to encrypt and decrypt strings using the cryptographic service provider version of the Triple Data Encryption Standard algorithm.

The use encryption to protect secret data and to make data unreadable by unauthorized users.

Creating encryption wrapper

  1. Open the previous project from this tutorial Write Text To File In Visual Basic then rename it to WriteTextToFileWithEncryptionVB or create a new project. I recommend to open the existing project to easily follow this tutorial.


  2. Create the Encryption3DesWrapper class to implement the encryption and decryption methods.

  3. 1
    2
    3
    Public NotInheritable Class Encryption3DesWrapper

    End Class

  4. Add an import of the cryptography namespace to the start of the file that contains the Encryption3DesWrapper class.

  5. 1
    2
    3
    4
    5
    Imports System.Security.Cryptography

    Public Class Encryption3DesWrapper

    End Class

  6. In the Encryption3DesWrapper class, add a private field to store the TripleDES cryptographic service provider.

  7. 1
    2
    3
    4
    5
    6
    Imports System.Security.Cryptography

    Public Class Encryption3DesWrapper
    Private TripleDesProvider As New TripleDESCryptoServiceProvider

    End Class

  8. Add a private method that creates a byte array of a specified length from the hash of the specified key.

  9.  1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    Imports System.Security.Cryptography

    Public Class Encryption3DesWrapper
    Private TripleDesProvider As New TripleDESCryptoServiceProvider

    Private Function TruncateHash(ByVal PassPhrase As String, ByVal Length As Integer) As Byte()
    Dim Sha1 As New SHA1CryptoServiceProvider

    Dim PassPhraseBytes() As Byte = System.Text.Encoding.Unicode.GetBytes(PassPhrase)
    Dim Hash() As Byte = Sha1.ComputeHash(PassPhraseBytes)

    ReDim Preserve Hash(Length - 1)
    Return Hash
    End Function

    End Class

  10. Add a constructor to initialize the TripleDES cryptographic service provider. The PassPhrase parameter controls the EncryptData and DecryptData methods.

  11.  1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    Imports System.Security.Cryptography

    Public Class Encryption3DesWrapper
    Private TripleDesProvider As New TripleDESCryptoServiceProvider

    Public Sub New(ByVal PassPhrase As String)
    TripleDesProvider.Key = TruncateHash(PassPhrase, TripleDesProvider.KeySize \ 8)
    TripleDesProvider.IV = TruncateHash("", TripleDesProvider.BlockSize \ 8)
    End Sub

    Private Function TruncateHash(ByVal PassPhrase As String, ByVal Length As Integer) As Byte()
    Dim Sha1 As New SHA1CryptoServiceProvider

    Dim PassPhraseBytes() As Byte = System.Text.Encoding.Unicode.GetBytes(PassPhrase)
    Dim Hash() As Byte = Sha1.ComputeHash(PassPhraseBytes)

    ReDim Preserve Hash(Length - 1)
    Return Hash
    End Function

    End Class

  12. Add a public method that encrypts a string.

  13.  1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    Imports System.Security.Cryptography

    Public Class Encryption3DesWrapper
    Private TripleDesProvider As New TripleDESCryptoServiceProvider

    Public Sub New(ByVal PassPhrase As String)
    TripleDesProvider.Key = TruncateHash(PassPhrase, TripleDesProvider.KeySize \ 8)
    TripleDesProvider.IV = TruncateHash("", TripleDesProvider.BlockSize \ 8)
    End Sub

    Private Function TruncateHash(ByVal PassPhrase As String, ByVal Length As Integer) As Byte()
    Dim Sha1 As New SHA1CryptoServiceProvider

    Dim PassPhraseBytes() As Byte = System.Text.Encoding.Unicode.GetBytes(PassPhrase)
    Dim Hash() As Byte = Sha1.ComputeHash(PassPhraseBytes)

    ReDim Preserve Hash(Length - 1)
    Return Hash
    End Function

    Public Function EncryptData(ByVal PlainTextData As String) As String

    Dim PlainTextBytes() As Byte = System.Text.Encoding.Unicode.GetBytes(PlainTextData)

    Dim ms As New System.IO.MemoryStream

    Dim Stream As New CryptoStream(ms, TripleDES.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write)

    Stream.Write(PlainTextBytes, 0, PlainTextBytes.Length)
    Stream.FlushFinalBlock()

    Return Convert.ToBase64String(ms.ToArray)
    End Function

    End Class

  14. Add a public method that decrypts a string.

  15.  1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    Imports System.Security.Cryptography

    Public Class Encryption3DesWrapper
    Private TripleDesProvider As New TripleDESCryptoServiceProvider

    Public Sub New(ByVal PassPhrase As String)
    TripleDesProvider.Key = TruncateHash(PassPhrase, TripleDesProvider.KeySize \ 8)
    TripleDesProvider.IV = TruncateHash("", TripleDesProvider.BlockSize \ 8)
    End Sub

    Private Function TruncateHash(ByVal PassPhrase As String, ByVal Length As Integer) As Byte()
    Dim Sha1 As New SHA1CryptoServiceProvider

    Dim PassPhraseBytes() As Byte = System.Text.Encoding.Unicode.GetBytes(PassPhrase)
    Dim Hash() As Byte = Sha1.ComputeHash(PassPhraseBytes)

    ReDim Preserve Hash(Length - 1)
    Return Hash
    End Function

    Public Function EncryptData(ByVal PlainTextData As String) As String

    Dim PlainTextBytes() As Byte = System.Text.Encoding.Unicode.GetBytes(PlainTextData)

    Dim ms As New System.IO.MemoryStream

    Dim Stream As New CryptoStream(ms, TripleDesProvider.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write)

    Stream.Write(PlainTextBytes, 0, PlainTextBytes.Length)
    Stream.FlushFinalBlock()

    Return Convert.ToBase64String(ms.ToArray)
    End Function

    Public Function DecryptData(ByVal EncryptedTextData As String) As String

    Dim EncryptedBytes() As Byte = Convert.FromBase64String(EncryptedTextData)

    Dim ms As New System.IO.MemoryStream

    Dim Stream As New CryptoStream(ms, TripleDesProvider.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write)

    Stream.Write(EncryptedBytes, 0, EncryptedBytes.Length)
    Stream.FlushFinalBlock()

    Return System.Text.Encoding.Unicode.GetString(ms.ToArray)
    End Function

    End Class


Using of the encryption wrapper

View the FormMain code and replace the with the code below and run it.

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
Public Class FormMain

Private EncryptionWrapper As Encryption3DesWrapper

Protected Const PassPhrase As String = "ANY_PHASSPHRASE_HERE"

Private Sub FormMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load

EncryptionWrapper = New Encryption3DesWrapper(PassPhrase)

End Sub

Private Sub ButtonWrite_Click(sender As Object, e As EventArgs) Handles ButtonWrite.Click

'Create new instance of SaveFileDialog
Using dlgSaveFile As New SaveFileDialog

'Start call on dlgSaveFile to optimize the coding
With dlgSaveFile


'Create InitialDirectory variable and get the My Documents folder path
Dim InitialDirectory As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)

'Set the initial directory
.InitialDirectory = InitialDirectory

'Set the file extention to filter
.Filter = "Text files (*.txt)|*.txt;"

'Set the restore directory
.RestoreDirectory = True

'Show the SaveFileDialog then check if the Save button was selected
If .ShowDialog = DialogResult.OK Then

'Create new instance of StreamWriter and create file
Using TextStreamWriter As New IO.StreamWriter(.FileName, False)

'Write the TextboxContianer content to file
TextStreamWriter.Write(EncryptionWrapper.EncryptData(TextBoxContainer.Text))

'Close the StreamWriter
TextStreamWriter.Close()

End Using
Else

'If Cancel button was click then
'Do nothing

End If

End With

End Using

End Sub

Private Sub FormMain_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing

EncryptionWrapper = Nothing

End Sub

End Class


Save the this project for the future tutorials and  that's all. I hope that you enjoy my tutorials.

Subscribe to this page for more.


Download WriteTextToFileWithEncryptionVB Project



Comments