dcsimg

Encrypting Important Strings with Triple DES and .NET

WEBINAR:
On-Demand

Desktop-as-a-Service Designed for Any Cloud ? Nutanix Frame


Introduction

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.

C#

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

VB.NET

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.

C#

   public class Simple3Des
   {
      private TripleDESCryptoServiceProvider tdDes = new
         TripleDESCryptoServiceProvider();
      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
            .GetBytes(strInput);
         System.IO.MemoryStream msInput = new System.IO
            .MemoryStream();
         CryptoStream csEncrypt = new CryptoStream(msInput,
            tdDes.CreateEncryptor(), CryptoStreamMode.Write);

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

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

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

         return System.Text.Encoding.Unicode
            .GetString(msOutput.ToArray());
      }
      private byte[] Truncate(string strKey, int intLength)
      {
         SHA1CryptoServiceProvider shaCrypto = new
            SHA1CryptoServiceProvider();
         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;
      }
   }

VB.NET

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 = _
         Text.Encoding.Unicode.GetBytes(strInput)
      Dim msInput As New IO.MemoryStream
      Dim csEncrypt As New CryptoStream(msInput, _
         tdDes.CreateEncryptor(), CryptoStreamMode.Write)

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

      Return Convert.ToBase64String(msInput.ToArray)

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

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

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

      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.

C#

     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";

VB.NET

    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 strWords As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    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.

C#

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

         string strFinal = strWords + strNumbers +
            strWords.ToLower();

            int intLength = 9;

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

               lstPlain.Add(strSubstring);
               ListBox1.Items.Add(strSubstring);
            }
      }

VB.NET

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

      Dim strFinal As String = strWords & strNumbers & _
         strWords.ToLower

      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, _
            intLength)

         lstPlain.Add(strSubstring)
         ListBox1.Items.Add(strSubstring)

      Next

   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.

C#

      private void Button1_Click(object sender, EventArgs e)
      {
         foreach (string str in lstPlain)
         {
            string strEncrypted = objSimpleDes.Encrypt(str);
            intItemLength.Add(strEncrypted.Length);
            lstEncoded.Add(strEncrypted);
         }

         ListBox2.DataSource = lstEncoded;
      }

VB.NET

   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)
         intItemLength.Add(strEncrypted.Length)
         lstEncoded.Add(strEncrypted)

      Next

      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.

Encrypted
Figure 2: Encrypted

Add the code to the decrypt button.

C#

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

         lstDecoded.Add(objSimpleDes.Decrypt(str));

         ListBox2.DataSource = lstDecoded;
      }

VB.NET

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

      For Each str As String In lstEncoded

         lstDecoded.Add(objSimpleDes.Decrypt(str))
      Next

      ListBox2.DataSource = lstDecoded

   End Sub

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

Decrypted
Figure 3: Decrypted

Conclusion

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.



About the Author

Hannes DuPreez

Hannes du Preez is a self-taught developer who started learning to program in the days of QBasic. He has written several articles over the years detailing his programming quests and adventures. .NET is his second love, just after his wife and kid. He has always been an avid supporter of .NET since the beginning and is an expert in VB and C#. He was given the Microsoft Most Valuable Professional Award for .NET (2008–2017). He has worked as a moderator and an article reviewer on online forums and currently works as a C# developer and writes articles for CodeGuru.com, Developer.com, DevX.com, and the Database journal. His first book, Visual Studio 2019 in Depth... is currently on sale on Amazon.com.

Related Articles

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date