Learn ASP.NET Core 2 and Angular 6 in October 2018. Instructor-led online courses by Bipin Joshi. Read more...
Instructor-led Online Courses by Bipin Joshi : ASP.NET Core | Angular | Design Patterns
Registration open for October 2018 batches. Read more here.

Cryptography and .NET Framework - Part 2 (Secret key Encryption)


In the Part 1 we learnt the basics of Cryptography and related .NET Framework classes. In this article we are going to see how to work with Secret Key Encryption using Triple-DES algorithm.


The System.Security.Cryptography namespace contains a class called TripleDESCryptoServiceProvider that provides Triple-DES encryption to your data. DES stands for Data Encryption Standard and the word triple is used because it encrypts the original data thrice.

The secret key encryption needs two things to encrypt the data:

  • A secret key
  • An initialization vector

The encryption algorithms employ use a chaining technique to encrypt the data. In this technique the entire data to be encrypted is divided in smaller blocks. The previously encrypted block of data is used to encrypt the current one and the process repeats.

The Initialization Vector (IV) serves as a seed that is used to encrypt and decrypt the first block of bytes. This ensures that no two blocks of data produce the same block of encrypted text.

For using TripleDESCryptoServiceProvider the encryption key must be of 24 bytes and the initialization vector must be of 8 bytes.

Example of using TripleDESCryptoServiceProvider class

In this example we will first create a class called SecurityHelper that will help us encrypt and decrypt string data. Here is the code for the class:

Imports System.Security.Cryptography
Imports System.IO
Imports System.Text
Public Class SecurityHelper
    Public Key() As Byte
    Public IV() As Byte
    Public Function Encrypt(ByVal strData As String) As Byte()
        Dim data() As Byte = ASCIIEncoding.ASCII.GetBytes(strData)
        Dim tdes As TripleDESCryptoServiceProvider = 
	New TripleDESCryptoServiceProvider
	If Key Is Nothing Then
		Key = tdes.Key
		IV = tdes.IV
		tdes.Key = Key
		tdes.IV = IV
	End If
        Dim encryptor As ICryptoTransform = 
        Dim ms As New MemoryStream
        Dim cs As CryptoStream = 
	New CryptoStream(ms, encryptor, CryptoStreamMode.Write)
        cs.Write(data, 0, data.Length)
        ms.Position = 0
        Dim result(ms.Length - 1) As Byte
        ms.Read(result, 0, ms.Length)
        Return result
    End Function
    Public Function Decrypt(ByVal data() As Byte) As String
        Dim tdes As TripleDESCryptoServiceProvider = 
	New TripleDESCryptoServiceProvider
        tdes.Key = Key
        tdes.IV = IV
        Dim decryptor As ICryptoTransform = 
        Dim ms As New MemoryStream
        Dim cs As CryptoStream = 
	New CryptoStream(ms, decryptor, CryptoStreamMode.Write)
        cs.Write(data, 0, data.Length)
        ms.Position = 0
        Dim result(ms.Length - 1) As Byte
        ms.Read(result, 0, ms.Length)
        Return ASCIIEncoding.ASCII.GetString(result)
    End Function
End Class

Let's examine the code step by step:

  • We create a class called SecurityHelper with two functions Encrypt() and Decrypt(). The former accepts the string to be encrypted and returns encrypted form of the string as a byte array. The later accepts the encrypted data in the form of a byte array and returns decrypted data as a string.
  • The class has two public variables of byte array type. They are used to assign the secret key and initialization vector.
  • In the Encrypt() function we first convert the string to be encrypted into a byte array using GetBytes() method.
  • We then create an instance of TripleDESCryptoServiceProvider class
  • The key and initialization vector can be supplied externally by you or TripleDESCryptoServiceProvider class can generate one automatically for you. If user has not supplied key and IV we call GenerateKey() and GenerateIV() methods respectively. These methods create a random key and IV automatically for you. We assign the generated key and IV to public variables Key and IV.
  • Then we call CreateEncryptor() method of TripleDESCryptoServiceProvider class and collect its return value in a variable of type ICryptoTransform. The ICryptoTransform interface defines the basic operations of cryptographic transformations.
  • We then create a memory stream. The encrypted data will be put inside this stream.
  • We also create a CryptoStream and pass the memory stream and the encryptor created above.
  • Next, we write the data to be encrypted to the CryptoStream object. The CryptoStream object stores the encrypted version of the data in the supplied memory stream.
  • Finally, we read the memory stream for encrypted data. Put that data in an array of bytes and return it to the caller.

Decryption process is similar but follows reverse path. The only major difference between encryption and decryption code is that in case of decryption we call CreateDecryptor() method of TripleDESCryptoServiceProvider class.


Complete source code along with a sample usage is available for download with this article (see top).


In this article we saw how TripleDESCryptoServiceProvider class can be used to encrypt and decrypt string data. With little or no modification you can reuse the class for your own requirements. Some common uses of this algorithm can be - storing passwords in database, string confidential data such as bank account numbers etc. in database. In the example above we used memory stream to put our data but you can also use FileStream to save the data to a disk file. In the next article we will see how to use public-key encryption.


Bipin Joshi is a software consultant, trainer, author and spiritual yoga mentor having 23+ years of experience in software development. He teaches private online courses in ASP.NET Core and Angular to individuals and small groups. He is a published author and has authored or co-authored books for Apress and Wrox press. Having embraced the Yoga way of life he also teaches Ajapa Yoga to interested individuals. To know more about him click here.

He will be teaching ASP.NET Core 2.1 and Angular 6.1 in October 2018. Click here for his online course schedule and more details.

Get connected : Twitter  Facebook  Google+  LinkedIn

Posted On : 03 July 2005

Tags : .NET Framework Security