Creating Your Own Encryption / Decryption Program Using VB.NET 2005

Introduction

These days, protecting your valuable information is absolutely vital.  Anything is possible.  hackers & crackers frequently try to find new ways to break programs and to find critical information, for their malicious purposes.  We shouldn't only care about hackers & crackers, we should be concerned about coworkers using ( or having access to ) your computer.  With this article, I will try my best to assist you in protecting valuable information such as Passwords, account numbers and so on. Before I continue, let me explain the complicated stuff :)

Encryption

Encryption is the translation of data into a secret code, ciphertext. This code is scrambled, and results in an unreadable ( at least by a normal person ) string of characters. There are 2 types of Encryption : Asymetric Asymmetric Encryption is a form of Encryption where keys come in pairs. What one key encrypts, only the other can decrypt. Asymmetric Encryption is also known as Public Key Cryptography, since users typically create a matching key pair, and make one public while keeping the other secret. Symetric Symmetric Encryption is an Encryption algorithm where the same key is used for both Encryption and Decryption. The key must be kept secret, and is shared by the message sender and recipient.

Decryption

Decryption is the process of decoding data that has been encrypted into a secret format. Decryption requires a secret key or password.

Encryption methods

Having a look into the System.Security.Cryptography namespace will give you great insight:
System.Security.Cryptography Namespace

Rijndael method

The Rijndael encryption algorithm has been designed to replace the aging DES algorithm. Like DES, it is a block cipher. It uses 128-bit, 192-bit or 256-bit keys. This implementation encrypts 128-bit blocks. ( DES used 56-bit keys and 64-bit blocks )

Hexadecimal

Hexadecimal (also base-16, hexa, or hex) is a numeral system with a radix, or base, of 16. It uses sixteen distinct symbols, most often the symbols 0-9 to represent values zero to nine, and A, B, C, D, E, F (or a through f) to represent values ten to fifteen.

Ascii

Definition:
ASCII

Acii Table:
ASCII codes

Creating Your Own Encryption / Decryption Program Using VB.NET 2005

Our sample program

Purpose 

Our sample program's function is to be able to write to and read from an encrypted file. What's happening is that, when the program is first loaded, we can enter our "secret" text, and save it with a name and password. To access this file again, we need to supply the correct filename and password again. What I've done, was to create an onscreen keyboard to assist us when entering a password, so people never actually type the password, they enter it with the mouse. What I've done further was to convert the selected Filename to Hexadecimal code, so that it's not that easily known; when I need to refer to the file again, I just decode the Hexadecimal code back to normal text. Sound exciting B? let's start!

Design

Create a new Windows Application and call it CryptoViewer.  CryptoViewer consists of two forms, so use the Project menu to add another Form to your project. 

Add the following controls to Form1, and set the following properties on Form1 - your main form :

Control Name Property Name Property Setting
Form Name frmCryptoViewer
  Text Crypto Viewer
  FormBorderStyle FixedDialog
  BackColor White
Button Name btnLoadFile
  Text Load File
Button Name btnCopy
  Text Copy
Button Name btnSave
  Text Save
Button Name btnExit
  Text Exit
TextBox Name txtCrypto
  AcceptsReturn True
  Font Arial, 9.75pt
  ForeColor MediumBlue
  HideSelection False
  MultiLine True
  ScrollBars Both
  WordWrap False
OpenFileDialog Name ofdCrypt
  FileName "" ( Empty String )

frmCryptoViewer should look the same as:

[frmCryptoViewer.png]

Figure 1 - frmCryptoViewer

Add the following controls to Form2, and set the following properties on Form2 - your password form :

Control Name Property Name Property Value
Form Name frmPass
  BackColor White
  Text Crypto Viewer Password Box
Button Name btnDone
  DialogResult OK
  Text Done

frmPass should look like:

[frmPassDesign.png]

Figure 2 - frmPass

Creating Your Own Encryption / Decryption Program Using VB.NET 2005

Coding

frmCryptoViewer

Import the following namespaces:

'Cryptography NameSpace
Imports System.Security.Cryptography
'For File Input & Output
Imports System.IO

Declare the following variables in General Declarations:

    'Original TextBox Text
    Private OrigText As String
    'New Text Entered
    Private NewText As String
    'Contents Have Changed
    Private FileTextChanged As Boolean
    'File Name To Open
    Private strFileName As String

Sub Procedures and Functions:

    ''' 
    ''' Creates The Encrypted File, With The Specified Password
    ''' On The Speciffied File
    ''' 
    ''' 
    ''' 
    ''' 
    ''' 
    Private Sub ApplyCrypt(ByVal strInFileName As String, ByVal strOutFileName As String, _
    ByVal strPassword As String)
        'If TextBox Text Changed
        If FileTextChanged Then
            'Create Password Key
            Dim TestValueBytes As Byte() = _
            System.Text.Encoding.ASCII.GetBytes("This Is A Test")

            Dim PassKey As Rfc2898DeriveBytes = New _
            Rfc2898DeriveBytes(strPassword, TestValueBytes)

            'Create Algorithm And Specify The Key And Pass
            Dim rmAlgo As RijndaelManaged = New RijndaelManaged
            rmAlgo.Key = PassKey.GetBytes(rmAlgo.KeySize / 8)
            rmAlgo.IV = PassKey.GetBytes(rmAlgo.BlockSize / 8)

            'Read Unencrypted File 
            Dim strSourceFile As FileStream = _
            New FileStream(strInFileName, FileMode.Open, FileAccess.Read)

            'Store Its Data
            Dim strData(strSourceFile.Length) As Byte
            strSourceFile.Read(strData, 0, CType(strSourceFile.Length, Integer))

            'Create ICryptoTransform And CryptoStream Objects 
            Dim ictEncryptor As ICryptoTransform = rmAlgo.CreateEncryptor
            'Get Output File
            Dim strDestFile As FileStream = New _
            FileStream(strOutFileName, FileMode.OpenOrCreate, FileAccess.Write)

            'Write The Encryption
            Dim csEncryptStream As CryptoStream = _
            New CryptoStream(strDestFile, ictEncryptor, CryptoStreamMode.Write)
            csEncryptStream.Write(strData, 0, strData.Length)

            'Close All File Handles
            csEncryptStream.Close()
            strSourceFile.Close()
            strDestFile.Close()
        End If
    End Sub

    ''' 
    ''' Gets The Encrypted File And Loads
    ''' Contents If Correct Details Were Supplied
    ''' 
    ''' 
    ''' 
    ''' 
    ''' 
    Private Sub LoadCrypt(ByVal strInFileName As String, ByVal strOutFileName As String, _
    ByVal strPassword As String)
        Try
            'Create Password Key
            Dim TestValueBytes As Byte() = _
            System.Text.Encoding.ASCII.GetBytes("This Is A Test")
            Dim PassKey As Rfc2898DeriveBytes = New _
            Rfc2898DeriveBytes(strPassword, TestValueBytes)

            'Create Algorithm And Specify The Key And Pass
            Dim rmAlgo As RijndaelManaged = New RijndaelManaged
            rmAlgo.Key = PassKey.GetBytes(rmAlgo.KeySize / 8)
            rmAlgo.IV = PassKey.GetBytes(rmAlgo.BlockSize / 8)


            Dim ictDecryptor As ICryptoTransform = rmAlgo.CreateDecryptor

            'Read Encrypted File
            Dim strSourceFile As FileStream = _
            New FileStream(strInFileName, FileMode.Open, FileAccess.Read)

            'Load Encryption
            Dim csDecryptStream As CryptoStream = _
            New CryptoStream(strSourceFile, ictDecryptor, CryptoStreamMode.Read)

            'Store Its Data
            Dim fileData(strSourceFile.Length) As Byte
            csDecryptStream.Read(fileData, 0, CType(strSourceFile.Length, Integer))

            'Get Destination File
            Dim strDestFile As FileStream = New FileStream(strOutFileName, _
            FileMode.OpenOrCreate, FileAccess.Write)

            'Write To destination File
            strDestFile.Write(fileData, 0, fileData.Length)

            'Close All File Handles
            csDecryptStream.Close()
            strSourceFile.Close()
            strDestFile.Close()

            'Load File Into TextBox
            txtCrypto.Text = File.ReadAllText(strOutFileName)
            txtCrypto.SelectionLength = 0
            txtCrypto.SelectionStart = 0

            'Detect Changes To Original Text
            OrigText = txtCrypto.Text
            NewText = txtCrypto.Text

            FileTextChanged = False

            'Wrong Password Supplied
        Catch ex As Exception
            MessageBox.Show("Wrong Password And / Or FileName Entered", "Crypto", _
            MessageBoxButtons.OK, MessageBoxIcon.Stop)
        End Try
    End Sub

    ''' 
    ''' Converts Normal Text To Hexadecimal
    ''' 
    ''' 
    ''' 
    ''' 
    Public Function ToHexStr(ByVal strNormal As String) As String

        'Get Text To Convert
        Dim arrBytes As Integer() = ConvertCharsToBytes(strNormal)

        'Creates New StringBuilder Object
        Dim sbHexBuilder As System.Text.StringBuilder = New System.Text.StringBuilder

        'Loop Through Characters
        'And Convert To Hex
        For i As Integer = 0 To arrBytes.Length - 1
            sbHexBuilder.Append(String.Format("{0:x2}", Hex(arrBytes(i))))
        Next

        'Return Hex String
        Return sbHexBuilder.ToString()
    End Function

    ''' 
    ''' Convert Normal Characters To Byte Objects
    ''' 
    ''' 
    ''' 
    ''' 
    Private Function ConvertCharsToBytes(ByVal strInput As String) As Integer()

        'Convert Each Normal Character To a Char Object
        Dim c As Char() = strInput.ToCharArray()

        'Create A Byte Array
        Dim arrBytes As Integer()

        'Store Character's Bytes Into Array
        ReDim arrBytes(c.Length() - 1)

        For i As Integer = 0 To c.Length() - 1
            arrBytes(i) = System.Convert.ToByte(c(i))
        Next

        'Return Byte Object
        Return arrBytes
    End Function

    ''' 
    ''' Convert Hexadecimal To Normal Text
    ''' 
    ''' 
    ''' 
    ''' 
    Private Function HexToStr(ByVal HexStr As String) As String
        'Create Objects
        Dim strCurrentChar As String
        Dim strASCII As Integer
        Dim strOutput As String

        'Loop Through Each Character
        Do While Len(HexStr) > 0
            'Get The Next Hex Number
            strCurrentChar = HexStr.Substring(0, 2)
            'Store It
            HexStr = HexStr.Substring(2)
            'Convert To Decimal
            strASCII = CInt(Val("&H" & strCurrentChar))
            'Convert To Normal Character
            strOutput &= Chr(strASCII)
        Loop

        'Return Decoded String
        Return strOutput
    End Function

Add the following Form events:

    Private Sub frmCryptoViewer_FormClosing(ByVal sender As Object, ByVal e _
    As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing

        'If Output.txt Exists Delete It
        If File.Exists("Output.txt") Then File.Delete("Output.txt")

    End Sub

    Private Sub frmCryptoViewer_Load(ByVal sender As System.Object, ByVal e _
    As System.EventArgs) Handles MyBase.Load

        btnSave.Enabled = False 'Disable Save
    End Sub

Add the following code for the btnLoadFile button:

    Private Sub btnLoadFile_Click(ByVal sender As System.Object, ByVal e _
    As System.EventArgs) Handles btnLoadFile.Click

        If ofdCrypt.ShowDialog = Windows.Forms.DialogResult.OK Then

            'Get FileName Entered
            strFileName = ofdCrypt.FileName
            strFileName = ToHexStr(strFileName) 'Convert To Hex

            Dim frmCryptoPass As New frmPass

            If frmCryptoPass.ShowDialog = Windows.Forms.DialogResult.OK Then

                'If Correct Password Supplied Load File
                LoadCrypt("Encrypted.enc", "Output.txt", frmCryptoPass.CryptoPass)
            End If

        End If

    End Sub

Add the following code for btnCopy:

    Private Sub btnCopy_Click(ByVal sender As System.Object, ByVal e _
    As System.EventArgs) Handles btnCopy.Click

        Clipboard.SetText(txtCrypto.SelectedText) 'Copy Selected Text
    End Sub

btnSave should look like the following:

    Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e _
    As System.EventArgs) Handles btnSave.Click

        'Save To Output.txt
        File.WriteAllText("Output.txt", txtCrypto.Text)

        Dim frmCryptoPass As New frmPass 'Launch Password Box
        If frmCryptoPass.ShowDialog = Windows.Forms.DialogResult.OK Then

            'Set Password For File
            ApplyCrypt("Output.txt", "Encrypted.enc", frmCryptoPass.CryptoPass)
        End If

    End Sub

btnExit:

    Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e _
    As System.EventArgs) Handles btnExit.Click

        Me.Close() 'Exit
    End Sub

Last but not least,ad the folowing event for txtCrypto:

    Private Sub txtCrypto_LostFocus(ByVal sender As Object, ByVal e _
    As System.EventArgs) Handles txtCrypto.LostFocus

        'Determine TextBox Text Change
        If Not String.Compare(OrigText, NewText) Then
            FileTextChanged = True

        End If
    End Sub

    Private Sub txtCrypto_TextChanged(ByVal sender As Object, ByVal e _
    As System.EventArgs) Handles txtCrypto.TextChanged

        'Determine TextBox Text Change
        If Not String.Compare(OrigText, NewText) Then

            'If Text Changed We Can Save
            btnSave.Enabled = True
        End If
    End Sub

frmPass

Declare the following variables:

    Public CryptoPass As String 'Holds Password

Add the following Form events:

    Private Sub frmPass_Load(ByVal sender As System.Object, ByVal e _
    As System.EventArgs) Handles MyBase.Load

        Dim btnAscii As Button 'Declare New Button Object

        Dim btnAsciiLeft As Integer = 10 'New Button's Left
        Dim btnAsciiTop As Integer = 10 'New Button's Top

        'Create Buttons Ranging From "Space" To "~"
        'This Would Allow Us To Work All Keyboard Buttons
        For i As Integer = Asc(" ") To Asc("~")
            btnAscii = New Button 'Initialise

            With btnAscii 'Set Properties
                .Name = "btn_" & Chr(i) 'Set Name
                .Text = Chr(i) 'Set Text
                .Size = New Size(25, 25) 'Set Size
                'Set Pos
                .Location = New Point(btnAsciiLeft, btnAsciiTop)
                .Tag = Chr(i) 'Set Tag

                'Shift Buttons To The Right
                btnAsciiLeft = btnAsciiLeft + 30

                If Chr(i) = "0" Then 'If At 0 Start New Line
                    btnAsciiTop = btnAsciiTop + 50
                    btnAsciiLeft = 10
                End If

                If Chr(i) = "A" Then 'If At A Start New Line
                    btnAsciiTop = btnAsciiTop + 50
                    btnAsciiLeft = 10
                End If

                If Chr(i) = "R" Then 'If At R Start New Line
                    btnAsciiTop = btnAsciiTop + 50
                    btnAsciiLeft = 10
                End If

                If Chr(i) = "c" Then 'If At c Start At New Line
                    btnAsciiTop = btnAsciiTop + 50
                    btnAsciiLeft = 10
                End If

                If Chr(i) = "t" Then 'If At t Start New Line
                    btnAsciiTop = btnAsciiTop + 50
                    btnAsciiLeft = 10
                End If

                'If At u Shift Buttons To The Right
                If Chr(i) = "u" Then
                    btnAsciiLeft = btnAsciiLeft + 105
                    btnAsciiTop = btnAsciiTop
                End If

                'If At } Shift Last Button To The Right
                If Chr(i) = "}" Then
                    btnAsciiLeft = btnAsciiLeft + 105
                    btnAsciiTop = btnAsciiTop
                End If

                .Visible = True 'Make Visible

            End With

            Me.Controls.Add(btnAscii) 'Add To Form

            'Create Event
            AddHandler btnAscii.Click, AddressOf btnAscii_click
        Next

    End Sub

Add the btnAscii event like this:

    Private Sub btnAscii_click(ByVal sender As System.Object, ByVal e _
    As System.EventArgs)

        'Store Clicked Button(s) In String Variable
        CryptoPass = (DirectCast(sender, Button).Text)
    End Sub

btnDone:

    Private Sub btnDone_Click(ByVal sender As System.Object, ByVal e _
    As System.EventArgs) Handles btnDone.Click

        Me.Dispose() 'Dispose This Form
    End Sub

Creating Your Own Encryption / Decryption Program Using VB.NET 2005

Implementation

When this program is run, frmCryptoViewer will be displayed and waiting for input.  You can enter all your sensitive information in here, it can be a username and password, it can be a love letter, it doesn't matter :).  Once all text has been input, you should save the document.  After you have clicked the Save button, your frmPass will show, and will look like Figure 3.  Here, you should click in your password.  Now, what's happening in the background?

A normal Textfile named Output.txt gets created.  The ApplyCrypt method then reads this document and applies the Rijndael encryption onto it, and now, creates the Encrypted.enc, and when the program exits, it deletes theOutput.txt file.

On the program's second run ( or anytime after the Encrypted.enc file has been created ), you should load the file by clicking on the Load File button.  Here you should select the name of the encrypted file you've saved - in our case, Encrypted.enc, as shown in Figure 4.

The Password box displays again, and only if you have clicked in the correct password, it will load the file, as displayed in Figure 5.  If you've clicked in the wrong password, you will be notified as Figure 6 shows.

With this article, I'm including my Encrypted.enc file with, the Password that you have to click in is HTG

[frmPass.png]

Figure 3 - frmPass, during run time

[OpenFile.png]

Figure 4 - Open Your File

[FileLoaded.png]

Figure 5 - The file is loaded

[WrongPass.png]

Figure 6 - Wrong password notification

Conclusion

I sincerely hope you have enjoyed this lesson on using the Rijndael Algorithm.  With the next parts I will try to explore more ways of doing encryption, and protecting your sensitive data.  Until next time, cheers!



About the Author

Hannes du Preez

Hannes du Preez is a Microsoft MVP for Visual Basic. He is a trainer at a South African-based company. He is the co-founder of hmsmp.co.za, a community for South African developers.

Downloads

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: October 29, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you interested in building a cognitive application using the power of IBM Watson? Need a platform that provides speed and ease for rapidly deploying this application? Join Chris Madison, Watson Solution Architect, as he walks through the process of building a Watson powered application on IBM Bluemix. Chris will talk about the new Watson Services just released on IBM bluemix, but more importantly he will do a step by step cognitive …

  • On-demand Event Event Date: October 23, 2014 Despite the current "virtualize everything" mentality, there are advantages to utilizing physical hardware for certain tasks. This is especially true for backups. In many cases, it is clearly in an organization's best interest to make use of physical, purpose-built backup appliances rather than relying on virtual backup software (VBA - Virtual Backup Appliances). Join us for this webcast to learn why physical appliances are preferable to virtual backup appliances, …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds