Encrypting Important Strings with Triple DES and .NET


It might be the year 2019, but it is unbelievable how many people still do not protect their data, as well as developers not protecting their company’s data. It is always a “I’ll do it tomorrow” or “It is not our priority” or “it is not necessary yet” type of answer you get.

Then, data gets lost or corrupted.

Well, you could have prevented it, or at least made it a bit more difficult for your data to be stolen. There is always a way to bypass security, yes, but, at least try to make it difficult for your data to get lost.

This is where encryption comes in. I have written many a year ago about encryption, but I haven’t given a proper example, at least I think. We will build a small application today which takes a few lines of text and encrypts or decrypts it.

Create a new Windows Forms project in either VB.NET or C#. Enlarge the form. Add two big listboxes and two buttons onto the form.

Add a new class to your project and name it Simple3Des, for example.

This class will contain the Encryption and decryption logic.

Add the following namespaces.


using System.Security.Cryptography;
using System.Text;


Imports System.Security.Cryptography
Imports System.Text

These two namespaces allow us to manipulate text in any manner and access cryptography classes such as TripleDES.

Add the rest of the class.


   public class Simple3Des
      private TripleDESCryptoServiceProvider tdDes = new
      public Simple3Des(string strKey)
         tdDes.Key = Truncate(strKey, tdDes.KeySize / 8);
         tdDes.IV = Truncate("", tdDes.BlockSize / 8);
      public string Encrypt(string strInput)
         byte[] btInputBytes = System.Text.Encoding.Unicode
         System.IO.MemoryStream msInput = new System.IO
         CryptoStream csEncrypt = new CryptoStream(msInput,
            tdDes.CreateEncryptor(), CryptoStreamMode.Write);

         csEncrypt.Write(btInputBytes, 0, btInputBytes.Length);

         return Convert.ToBase64String(msInput.ToArray());
      public string Decrypt(string strOutput)
         byte[] btOutputBytes = Convert
         System.IO.MemoryStream msOutput = new
         CryptoStream csDecrypt = new CryptoStream(msOutput,
            tdDes.CreateDecryptor(), CryptoStreamMode.Write);

         csDecrypt.Write(btOutputBytes, 0, btOutputBytes.Length);

         return System.Text.Encoding.Unicode
      private byte[] Truncate(string strKey, int intLength)
         SHA1CryptoServiceProvider shaCrypto = new
         byte[] btKeyBytes = Encoding.Unicode.GetBytes(strKey);
         byte[] btHash = shaCrypto.ComputeHash(btKeyBytes);
         var oldBtHash = btHash;
         btHash = new byte[intLength - 1 + 1];
         if (oldBtHash != null)
            Array.Copy(oldBtHash, btHash, Math.Min(intLength - 1 +
               1, oldBtHash.Length));
         return btHash;


Public Class Simple3Des

   Private tdDes As New TripleDESCryptoServiceProvider
   Sub New(ByVal strKey As String)

      dDes.Key = Truncate(strKey, tdDes.KeySize \ 8)
      tdDes.IV = Truncate("", tdDes.BlockSize \ 8)

   End Sub
   Public Function Encrypt(ByVal strInput As String) As String

      Dim btInputBytes() As Byte = _
      Dim msInput As New IO.MemoryStream
      Dim csEncrypt As New CryptoStream(msInput, _
         tdDes.CreateEncryptor(), CryptoStreamMode.Write)

      csEncrypt.Write(btInputBytes, 0, btInputBytes.Length)

      Return Convert.ToBase64String(msInput.ToArray)

   End Function
   Public Function Decrypt(ByVal strOutput As String) As String

      Dim btOutputBytes() As Byte = _
      Dim msOutput As New IO.MemoryStream
      Dim csDecrypt As New CryptoStream(msOutput, _
         tdDes.CreateDecryptor(), CryptoStreamMode.Write)

      csDecrypt.Write(btOutputBytes, 0, btOutputBytes.Length)

      Return Text.Encoding.Unicode.GetString(msOutput.ToArray)

   End Function
   Private Function Truncate(ByVal strKey As String, _
         ByVal intLength As Integer) As Byte()

      Dim shaCrypto As New SHA1CryptoServiceProvider
      Dim btKeyBytes() As Byte = Encoding.Unicode.GetBytes(strKey)
      Dim btHash() As Byte = shaCrypto.ComputeHash(btKeyBytes)

      ReDim Preserve btHash(intLength - 1)
      Return btHash

   End Function
End Class

The Truncate function makes use of the SHA1CryptoServiceProvider, and then its ComputeHash method to provide the bytes to the Encrypt function. The Encrypt function converts the result into a Base64 string that scrambles the text. Decrypt takes the Base64 string and converts it back to a normal string.

Let’s add some code to the form.

Add the following fields to your form.


     private string strKey = "EncypherKey";
     private Simple3Des objSimpleDes;
     private List<string> lstPlain = new List<string>();
     private List<string> lstEncoded = new List<string>();
     private List<string> lstDecoded = new List<string>();
     private List<int> intItemLength = new List<int>();
     private Random rnd = new Random();
     private string strWords = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
     private string strNumbers = "1234567890";


    Dim strKey As String = "EncypherKey"
    Dim objSimpleDes As New Simple3Des(strKey)
    Dim lstPlain As New List(Of String)
    Dim lstEncoded As New List(Of String)
    Dim lstDecoded As New List(Of String)
    Dim intItemLength As New List(Of Integer)
    Dim rnd As New Random
    Dim strNumbers As String = "1234567890"

We create a key to be used as a cypher. Then, we create several String lists to hold the encryption results, the decryption results, as well as the normal text we start off with.

Add the following code in your Form_Load event.


      public void Form1_Load(object sender, EventArgs e)
         objSimpleDes = new Simple3Des(strKey);

         string strFinal = strWords + strNumbers +

            int intLength = 9;

            for (int i = 0; i <= 999; i++)
               int iStart = rnd.Next(0, strFinal.Length -
                  intLength + 1);
               string strSubstring = strFinal.Substring(iStart,



    Sub Form1_Load(sender As Object, e As EventArgs) Handles _

      Dim strFinal As String = strWords & strNumbers & _

      Dim intLength As Integer = 9

      For i As Integer = 0 To 999

         Dim iStart As Integer = rnd.Next(0, strFinal.Length - _
            intLength + 1)

         Dim strSubstring As String = strFinal.Substring(iStart, _



   End Sub

The Form_Load procedure is used to populate the first listbox with a bunch of random strings, as shown in Figure 1.

Form Load
Figure 1: Form Load

These strings will be encrypted. This we will do now. Add the following code.


      private void Button1_Click(object sender, EventArgs e)
         foreach (string str in lstPlain)
            string strEncrypted = objSimpleDes.Encrypt(str);

         ListBox2.DataSource = lstEncoded;


   Private Sub Button1_Click(sender As Object, e As EventArgs) _
         Handles Button1.Click

      For Each str As String In lstPlain

         Dim strEncrypted As String = objSimpleDes.Encrypt(str)


      ListBox2.DataSource = lstEncoded

    End Sub

When the encrypt button is clicked, it loops through each item in the list and encrypts it. Finally, it links the second listbox with the encrypted strings, as shown in Figure 2.

Figure 2: Encrypted

Add the code to the decrypt button.


      private void Button2_Click(object sender, EventArgs e)
         foreach (string str in lstEncoded)


         ListBox2.DataSource = lstDecoded;


   Private Sub Button2_Click(sender As Object, e As EventArgs) _
         Handles Button2.Click

      For Each str As String In lstEncoded


      ListBox2.DataSource = lstDecoded

   End Sub

The encrypted list simply gets decrypted and shown inside ListBox2, as shown in Figure 3.

Figure 3: Decrypted


Encrypting data becomes more and more crucial to any app. In this article, you have learned how to quickly encrypt and decrypt data by using a good cryptography function.

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