Skip to main content

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

Popular posts from this blog

Micom SE Studio1 Import Filter - Creating User Interface (UI)

Welcome to my page and welcome to the continuation of Omicron Import Filter tutorial series. In this tutorial, I will show you how to create the actual import filter fom Micom relays. In this tutorial, we will focus on the Visual Studio program. We're going to modify the codes in our project called MyImportFilter that we've created in the previous tutorial.  Download the project in this link  MyImportFilter - Process Relay Setting Parameters . Extract and open the project. Once the project is loaded, add New Folder inside the project and set the name to SEStudio1. We need this to make organize our project class filter.  SE Studio 1 stands for Schneider Electric Studio 1 which is the software that used in communicating MiCOM relays particularly P12x series. And yes we're going to create a new import filter and user interface form MiCOM P12x series relay. I think this will applied to other MiCOM P series relay. Add a new Form inside the  SEStudio1 folder...

Install And Use Newly Created Import Filter In Omicron Test Universe

Welcome to my page. This is the second part of the Omicron Import Filter tutorial series. In this tutorial, I will show you how install  and use the Import Filter that we've created in the previous tutorial in this series using two methods.  The first one via Test Object and the second one is via script. Open the Visual Studio project called MyImportFilter that we created in the first part of tutorial which can be found here ( Omicron Import Filter - Create New Filter ). Once the project opened, right click on the project at the solution explorer the click Open Folder in File Explorer. The project file directory will open. Open the  bin\Debug folder and you will find the two files in that folder ( MyImportFilter.dll and  SampleFilter.xriofilter ). Create new folder in that directory and set the folder name to  MyImportFilter . Move the  MyImportFilter.dll file to the  MyImportFilter folder then, copy the  MyImportFilter folder and the  Sa...

Change Data With Feedback In Omicron Control Center Custom Dialog

Welcome to the fifth and final part of the tutorial series about Omicron Control Center (OCC) Custom Dialog. In this tutorial, I will show you how to get a real-time feedback when data was change. This will be helpful that you will be notified what will be the outcome of the changed data. Check the video below. Now, open the OCC document that we used in the previous tutorial. If you don't have it check this link ( Omicron Control Center Custom Dialog - Creating Custom Dialog With Dropdown Control ) then come back here once you have OCC document. When the document is loaded, open the script view by clicking the Script View button under the View tab then stop the script if its running. Now, find the  SetTheSourceController sub procedure. We're going to modify this codes and use different methods of loading data from the test object and saving back to test object. Point the mouse pointer and click between  Begin Dialog and  End Dialog then click the Edit Dialog button un...