Doing Cryptography in Visual Basic

Introduction

Without a form of cryptography, your data will not be protected from outside influences such as hacking. It is always a good idea to encrypt information such as passwords or any sensitive information that you want to protect. Today, I will explain various forms of encryption in Visual Basic and the differences among them.

Cryptography

Cryptography is the practice of techniques for secure communication in the presence of third parties or adversaries. Cryptography is about constructing protocols that prevent adversaries from reading private electronic messages. Here are some of the various varieties of cryptographic approaches.

Caesar Cipher

A Caesar cipher is one of the simplest forms of encryption. Each letter in the original message (or plaintext) is simply replaced with a letter corresponding to a certain specified number of letters up or down in the alphabet.

AES Encryption

Advanced Encryption Standard (AES) is a symmetric encryption algorithm. AES can be used in both hardware and software, and supports a block length of 128 bits and key lengths of 128, 192, and 256 bits.

DES Encryption

DES (Data Encryption Standard) is a symmetric-key block cipher. DES uses a 16 round Feistel structure. The block size is 64-bit.

Rijndael Encryption

Rijndael is a block cipher with variable key length, variable block size, and variable round numbering. Block length and key length can be specified independently to any multiple of 32 bits from 128 bits to 256 bits. In s Rijndael AES variant, the block size is restricted to 128 bits and key length to 128, 192, or 256 bits only.

Our Project

Start Visual Studio and create a new Visual Basic Windows Forms application. Once the form is displayed, add five Buttons onto it, as shown in Figure 1. You are welcome to name your objects anything you like; just keep in mind that my names may differ from yours. I have kept the default names.

Design
Figure 1: Our Design

Namespaces

Add the following namespaces to your application:

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

Caesar Cipher

Add the following code to encrypt text with a Caesar Cipher:

   Public Shared Function CaesarCipher(ByVal strInput As String, _
         ByVal intShift As Integer, Optional ByVal strCharacterSet _
         As String = "abcdefghijklmnopqrstuvwxyz" & _
         "ABCDEFGHIJKLMNOPQRSTUVWXYZ" & " ") As String
      Dim sbEncrypt As New StringBuilder With {.Capacity = strInput.Length}
      For Each c As Char In strInput
         Dim intChar As Integer = strCharacterSet.IndexOf(c)
         Do Until (intChar + intShift) < (strCharacterSet.Length)
            intChar -= strCharacterSet.Length
         Loop
         sbEncrypt.Append(strCharacterSet(intChar + intShift))
      Next c
      Return sbEncrypt.ToString
   End Function

This code takes the input text and replaces it with a character set. This character set is obviously the common alphabet as we know it, in upper- and lower-case letters. Depending on the intShift parameter, IKT will replace the input text with the associated characters at the given location. Add the next code to decrypt the Caesar Cipher:

   Public Shared Function CaesarDecipher(ByVal strInput As String, _
         ByVal intShift As Integer, Optional ByVal strCharacterSet _
         As String = "abcdefghijklmnopqrstuvwxyz" & _
         "ABCDEFGHIJKLMNOPQRSTUVWXYZ" & " ") As String
      Return CaesarCipher(strInput, intShift, String.Join("", _
         strCharacterSet.Reverse))
   End Function

The preceding code simply replaces the encrypted text with a known character set. To implement this functionality, add the following code under the button labeled ‘Caesar Cipher‘:

   Private Sub Button1_Click(sender As Object, e As EventArgs) _
         Handles Button1.Click
      Dim strValue As String = "My Name is Hannes"
      Dim strEncrypted As String = _
         CaesarCipher(strValue, intShift:=15)
      Dim strDecrypted As String = _
         CaesarDecipher(strEncrypted, intShift:=15)
      Debug.WriteLine(String.Format("Entered string: {0}", _
         strValue))
      Debug.WriteLine(String.Format("Encrypted  string: {0}", _
         strEncrypted))
      Debug.WriteLine(String.Format("Decrypted string: {0}", _
         strDecrypted))
   End Sub

This sub simply shows the entered text, the encrypted text, and the decrypted text.

AES

Add the following code that uses AES to encrypt information:

   Shared Function Encrypt_Aes(ByVal strInput As String, _
         ByVal btKey() As Byte, ByVal btIV() As Byte) As Byte()
      Dim btEncrypt() As Byte
      Using aesAlg As Aes = Aes.Create()
         aesAlg.Key = btKey
         aesAlg.IV = btIV
         Dim ictEncryptor As ICryptoTransform = _
            aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV)
         Using msEncrypt As New MemoryStream()
            Using csEncrypt As New CryptoStream(msEncrypt, _
                  ictEncryptor, CryptoStreamMode.Write)
               Using swEncrypt As New StreamWriter(csEncrypt)
                  swEncrypt.Write(strInput)
               End Using
               btEncrypt = msEncrypt.ToArray()
            End Using
         End Using
      End Using
      Return btEncrypt
   End Function

This function takes a string input and does AES encryption on the given string. This results in a byte array that gets outputted by the function. Add the next piece of code to decrypt the AES-encrypted byte array:

   Shared Function Decrypt_Aes(ByVal btCipher() As Byte, _
         ByVal btKey() As Byte, ByVal btIV() As Byte) As String
      Dim strResult As String = Nothing
      Using objAes As Aes = Aes.Create()
         objAes.Key = btKey
         objAes.IV = btIV
         Dim ictDecryptor As ICryptoTransform = _
            objAes.CreateDecryptor(objAes.Key, objAes.IV)
         Using msDecrypt As New MemoryStream(btCipher)
            Using csDecrypt As New CryptoStream(msDecrypt, _
                  ictDecryptor, CryptoStreamMode.Read)
               Using srDecrypt As New StreamReader(csDecrypt)
                  strResult = srDecrypt.ReadToEnd()
               End Using
            End Using
         End Using
      End Using
      Return strResult
   End Function

This function creates an AES decryptor that ultimately translates the given byte array into legible text. Add the following code behind the button labeled ‘Aes‘ to set the AES encryption and decryption in motion:

   Private Sub Button2_Click(sender As Object, e As EventArgs) _
         Handles Button2.Click
      Dim strInput As String = "My name is Hannes"
      Using objAes As Aes = Aes.Create()
         Dim btEncrypt As Byte() = Encrypt_Aes(strInput, _
            objAes.Key, objAes.IV)
         Dim strDecrypt As String = Decrypt_Aes(btEncrypt, _
            objAes.Key, objAes.IV)
         Console.WriteLine("Entered String: {0}", strInput)
         Console.WriteLine("Encrypted Bytes: {0}", _
            btEncrypt.ToString())
         Console.WriteLine("Decrypted String: {0}", strDecrypt)
      End Using
   End Sub

This code simply enables the encrypt and decrypt processes and displays the results in the output window.

DES

Add the following code to encrypt data using DES:

   Shared Function Encrypt_DES(ByVal strInput As String, _
         ByVal btKey() As Byte, ByVal btIV() As Byte) As Byte()
      Dim btEncrypt() As Byte
      Using tdcDES As New TripleDESCryptoServiceProvider()
         tdcDES.Key = btKey
         tdcDES.IV = btIV
         Dim ictEncryptor As ICryptoTransform = _
            tdcDES.CreateEncryptor(tdcDES.Key, tdcDES.IV)
         Using msEncrypt As New MemoryStream()
            Using csEncrypt As New CryptoStream(msEncrypt, _
                  ictEncryptor, CryptoStreamMode.Write)
               Using swEncrypt As New StreamWriter(csEncrypt)
                  swEncrypt.Write(strInput)
               End Using
               btEncrypt = msEncrypt.ToArray()
            End Using
         End Using
      End Using
      Return btEncrypt
   End Function

This function resembles the previous encryption function (Encrypt_Aes). It is intentional and it is so that you can see how that encrypting data is simple, regardless of which encryption you decide to employ. The above code uses DES to encrypt data into a byte array. Add the decrypting function:

   Shared Function Decrypt_DES(ByVal btCipher() As Byte, _
         ByVal btKey() As Byte, ByVal btIV() As Byte) As String
      Dim strResult As String = Nothing
      Using tdcDES As New TripleDESCryptoServiceProvider
         tdcDES.Key = btKey
         tdcDES.IV = btIV
         Dim ictDecryptor As ICryptoTransform = _
            tdcDES.CreateDecryptor(tdcDES.Key, tdcDES.IV)
         Using msDecrypt As New MemoryStream(btCipher)
            Using csDecrypt As New CryptoStream(msDecrypt, _
                  ictDecryptor, CryptoStreamMode.Read)
               Using srDecrypt As New StreamReader(csDecrypt)
                  strResult = srDecrypt.ReadToEnd()
               End Using
            End Using
         End Using
      End Using
      Return strResult
   End Function

This decrypts the DES-encrypted data into an ordinary string. Add the button that makes use of the DES encryption and decryption:

   Private Sub Button3_Click(sender As Object, e As EventArgs) _
         Handles Button3.Click
      Dim strEncrypt As String = "My name is Hannes"
      Using tdcDES As New TripleDESCryptoServiceProvider()
         Dim btEncrypt As Byte() = Encrypt_DES(strEncrypt, _
            tdcDES.Key, tdcDES.IV)
         Dim strDecrypt As String = Decrypt_DES(btEncrypt, _
            tdcDES.Key, tdcDES.IV)
         Console.WriteLine("Entered String: {0}", strEncrypt)
         Console.WriteLine("Encrypted: {0}", _
            btEncrypt.ToString())
         Console.WriteLine("Decrypted: {0}", strDecrypt)
      End Using
   End Sub

Rijndael

Add the following code for Rijndael encryption and decryption:

   Shared Function Encrypt_Rijndael(ByVal strInput As String, _
         ByVal btKey() As Byte, ByVal btIV() As Byte) As Byte()
      Dim btEncrypt() As Byte
      Using objRijndael = Rijndael.Create()
         objRijndael.Key = btKey
         objRijndael.IV = btIV
         Dim ictEncrypt As ICryptoTransform = _
            objRijndael.CreateEncryptor(objRijndael.Key, objRijndael.IV)
         Using msEncrypt As New MemoryStream()
            Using csEncrypt As New CryptoStream(msEncrypt, ictEncrypt, _
                  CryptoStreamMode.Write)
               Using swEncrypt As New StreamWriter(csEncrypt)
                  swEncrypt.Write(strInput)
               End Using
               btEncrypt = msEncrypt.ToArray()
            End Using
         End Using
      End Using
      Return btEncrypt
   End Function
   Shared Function Decrypt_Rijndael(ByVal btCipher() As Byte, _
         ByVal btKey() As Byte, ByVal btIV() As Byte) As String
      Dim strResult As String = Nothing
      Using objRijndael = Rijndael.Create()
         objRijndael.Key = btKey
         objRijndael.IV = btIV
         Dim ictDecrypt As ICryptoTransform = _
            objRijndael.CreateDecryptor(objRijndael.Key, objRijndael.IV)
         Using msDecrypt As New MemoryStream(btCipher)
            Using csDecrypt As New CryptoStream(msDecrypt, _
                  ictDecrypt, CryptoStreamMode.Read)
               Using srDecrypt As New StreamReader(csDecrypt)
                  strResult = srDecrypt.ReadToEnd()
               End Using
            End Using
         End Using
      End Using
      Return strResult
   End Function
   Private Sub Button4_Click(sender As Object, e As EventArgs) _
         Handles Button4.Click
      Dim strInput As String = "My name is Hannes"
      Using myRijndael = Rijndael.Create()
         Dim btEncrypt As Byte() = Encrypt_Rijndael(strInput, _
            myRijndael.Key, myRijndael.IV)
         Dim strResult As String = Decrypt_Rijndael(btEncrypt, _
            myRijndael.Key, myRijndael.IV)
         Console.WriteLine("Entered String: {0}", strInput)
         Console.WriteLine("Encrypted: {0}", _
            btEncrypt.ToString())
         Console.WriteLine("Decrypted: {0}", strResult)
      End Using
   End Sub

TripleDES

Add the following code to encrypt data using TripleDES:

   Public Function EncryptTripleDES(strInput As String, _
         btKey As String) As String
      Dim desTDES As New TripleDESCryptoServiceProvider()
      Dim hashMD5TDES As New MD5CryptoServiceProvider()
      Dim btHash As Byte()
      Dim btBuff As Byte()
      btHash = hashMD5TDES.ComputeHash(Encoding.UTF8.GetBytes(btKey))
      desTDES.Key = btHash
      desTDES.Mode = CipherMode.ECB
      btBuff = Encoding.UTF8.GetBytes(strInput)
      Dim strResult As String = Convert.ToBase64String _
         (desTDES.CreateEncryptor().TransformFinalBlock(btBuff, 0, _
          btBuff.Length))
      Return strResult
   End Function

This works a bit differently than the others. Here, I created a TripleDES object and created a new MD5 Hash via the MD5Hash object. I give the DES object a key for encryption, and then convert the data to a Base 64 string (please see “Displaying 64bit String Images in Visual Basic“).

Add the following code to decrypt this data:

   Public Shared Function DecryptTripleDES(strInput As String, _
         btKey As String) As String
      Dim desTDES As New TripleDESCryptoServiceProvider()
      Dim hashMD5TDES As New MD5CryptoServiceProvider()
      Dim btHash As Byte()
      Dim btBuff As Byte()
      btHash = hashMD5TDES.ComputeHash(Encoding.UTF8.GetBytes(btKey))
      desTDES.Key = btHash
      desTDES.Mode = CipherMode.ECB
      btBuff = Convert.FromBase64String(strInput)
      Dim strResult As String = Encoding.UTF8.GetString _
         (desTDES.CreateDecryptor().TransformFinalBlock(btBuff, 0, _
          btBuff.Length))
      Return strResult
   End Function

It follows the same principle as the encrypting function except that it is now decrypting and reading the source data from a Base64 string. Add the code behind the button labeled ‘TripleDES‘ to put this in motion:

   Private Sub Button5_Click(sender As Object, e As EventArgs) _
         Handles Button5.Click
      Dim strEncode As String = EncryptTripleDES("My name is Hannes", _
         "HTG")
      Dim strDecode As String = DecryptTripleDES(strEncode, "HTG")
      Console.WriteLine("Encrypted: {0}", strEncode)
      Console.WriteLine("Decrypted: {0}", strDecode)
   End Sub

Conclusion

Knowing how to encrypt and decrypt information is vital. I hope you have learned a great deal today.

Hannes DuPreez
Hannes DuPreez
Ockert J. du Preez is a passionate coder and always willing to learn. He has written hundreds of developer articles over the years detailing his programming quests and adventures. He has written the following books: Visual Studio 2019 In-Depth (BpB Publications) JavaScript for Gurus (BpB Publications) He was the Technical Editor for Professional C++, 5th Edition (Wiley) He was a Microsoft Most Valuable Professional for .NET (2008–2017).

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read