TripleDES Encryption In C# And .NET Core

TripleDES Encryption In C#

.NET provides high level classes for various encryption algorithms, both symmetric and asymmetric. Data Encryption Standard (DES) is one of the symmetric encryption algorithms that allows both parties, sender and receiver, to use same key to encrypt and decrypt data.

DES was developed by IBM in 1975. It is considered as an insecure algorithm due to its key size 56 bits and block size 64 bits. However, it successor, Triple DES (3DES) is secure. TripleDES applies DES algorithm 3 times on each block.

TripleDesCryptoServiceProvider class provides the functionality of TripleDES algorithm. This article demonstrates how to use TripleDesCryptoServiceProvider class to apply DES algorithm to encrypt and decrypt data in .NET and C#.

The following steps are required to encrypt data using the TripleDES algorithm.

Step 1

Create TripleDESCryptoServiceProvider,
  1. TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();  
Step 2

Create an Encryptor,
  1. ICryptoTransform encryptor = tdes.CreateEncryptor(Key, IV);  
Step 3

Create a MemoryStream,
  1. MemoryStream ms = new MemoryStream();  
Step 4

Create a CryptoStream from MemoryStream and Encrypter and write it.
  1. using(CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))  
  2. {  
  3.     // Create StreamWriter and write data to a stream  
  4.     using(StreamWriter sw = new StreamWriter(cs))  
  5.     sw.Write(plainText);  
  6.     encrypted = ms.ToArray();  
  7. }  
The complete code is listed in Listing 1.
  1. using System;  
  2. using System.IO;  
  3. using System.Security.Cryptography;  
  4. class TripleDESSample {  
  5.     public static void Main() {  
  6.         Console.WriteLine("Enter text that needs to be encrypted..");  
  7.         string data = Console.ReadLine();  
  8.         Apply3DES(data);  
  9.         Console.ReadLine();  
  10.     }  
  11.     static void Apply3DES(string raw) {  
  12.         try {  
  13.             // Create 3DES that generates a new key and initialization vector (IV).  
  14.             // Same key must be used in encryption and decryption  
  15.             using(TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider()) {  
  16.                 // Encrypt string  
  17.                 byte[] encrypted = Encrypt(raw, tdes.Key, tdes.IV);  
  18.                 // Print encrypted string  
  19.                 Console.WriteLine($ "Encrypted data: {System.Text.Encoding.UTF8.GetString(encrypted)}");  
  20.                 // Decrypt the bytes to a string.  
  21.                 string decrypted = Decrypt(encrypted, tdes.Key, tdes.IV);  
  22.                 // Print decrypted string. It should be same as raw data  
  23.                 Console.WriteLine($ "Decrypted data: {decrypted}");  
  24.             }  
  25.         } catch (Exception exp) {  
  26.             Console.WriteLine(exp.Message);  
  27.         }  
  28.         Console.ReadKey();  
  29.     }  
  30.     static byte[] Encrypt(string plainText, byte[] Key, byte[] IV) {  
  31.         byte[] encrypted;  
  32.         // Create a new TripleDESCryptoServiceProvider.  
  33.         using(TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider()) {  
  34.             // Create encryptor  
  35.             ICryptoTransform encryptor = tdes.CreateEncryptor(Key, IV);  
  36.             // Create MemoryStream  
  37.             using(MemoryStream ms = new MemoryStream()) {  
  38.                 // Create crypto stream using the CryptoStream class. This class is the key to encryption  
  39.                 // and encrypts and decrypts data from any given stream. In this case, we will pass a memory stream  
  40.                 // to encrypt  
  41.                 using(CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write)) {  
  42.                     // Create StreamWriter and write data to a stream  
  43.                     using(StreamWriter sw = new StreamWriter(cs))  
  44.                     sw.Write(plainText);  
  45.                     encrypted = ms.ToArray();  
  46.                 }  
  47.             }  
  48.         }  
  49.         // Return encrypted data  
  50.         return encrypted;  
  51.     }  
  52.     static string Decrypt(byte[] cipherText, byte[] Key, byte[] IV) {  
  53.         string plaintext = null;  
  54.         // Create TripleDESCryptoServiceProvider  
  55.         using(TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider()) {  
  56.             // Create a decryptor  
  57.             ICryptoTransform decryptor = tdes.CreateDecryptor(Key, IV);  
  58.             // Create the streams used for decryption.  
  59.             using(MemoryStream ms = new MemoryStream(cipherText)) {  
  60.                 // Create crypto stream  
  61.                 using(CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read)) {  
  62.                     // Read crypto stream  
  63.                     using(StreamReader reader = new StreamReader(cs))  
  64.                     plaintext = reader.ReadToEnd();  
  65.                 }  
  66.             }  
  67.         }  
  68.         return plaintext;  
  69.     }  
  70.     private static void EncryptFile(String inName, String outName, byte[] desKey, byte[] desIV) {  
  71.         //Create the file streams to handle the input and output files.  
  72.         FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read);  
  73.         FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write);  
  74.         fout.SetLength(0);  
  75.         //Create variables to help with read and write.  
  76.         byte[] bin = new byte[100]; //This is intermediate storage for the encryption.  
  77.         long rdlen = 0; //This is the total number of bytes written.  
  78.         long totlen = fin.Length; //This is the total length of the input file.  
  79.         int len; //This is the number of bytes to be written at a time.  
  80.         DES des = new DESCryptoServiceProvider();  
  81.         CryptoStream encStream = new CryptoStream(fout, des.CreateEncryptor(desKey, desIV), CryptoStreamMode.Write);  
  82.         Console.WriteLine("Encrypting...");  
  83.         //Read from the input file, then encrypt and write to the output file.  
  84.         while (rdlen < totlen) {  
  85.             len = fin.Read(bin, 0, 100);  
  86.             encStream.Write(bin, 0, len);  
  87.             rdlen = rdlen + len;  
  88.             Console.WriteLine("{0} bytes processed", rdlen);  
  89.         }  
  90.         encStream.Close();  
  91.         fout.Close();  
  92.         fin.Close();  
  93.     }  
  94. }  
Listing 1
 
TripleDES Encryption 
Figure 1

References
  • https://en.wikipedia.org/wiki/Data_Encryption_Standard
  • https://docs.microsoft.com


Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.