How to Encryption/Decryption in C#

Using the built in crypto classes in .NET can be surprisingly complicated. You need a lot of understanding of what you are doing to get it right and how to work in a secure manner. The choice of algorithm, what cipher mode, key length, block size and understand what salt is and how to use it and also how to hash a password to a proper key are some things you need to deal with. Hopefully, this article will make your life a lot easier.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Drawing;  
  6. using System.Linq;  
  7. using System.Text;  
  8. using System.Windows.Forms;  
  9. using System.Security.Cryptography;  
  10. using System.IO;  
  11. namespace EncryptionDeMO  
  12. {  
  13.    public partial class Form1 : Form  
  14.    {  
  15.       public Form1()  
  16.       {  
  17.          InitializeComponent();  
  18.       }  
  19.       private void button1_Click(object sender, EventArgs e)  
  20.       {  
  21.          textBox2.Text = Encrypt(textBox1.Text, "sanketshinde@12345678912"); //key size should be 128bits or 192 bits only  
  22.       }  
  23.       #region Encrypt and Decrypt code  
  24.       public string Encrypt(string input, string key)  
  25.       {  
  26.          byte[] inputArray = UTF8Encoding.UTF8.GetBytes(input);  
  27.          TripleDESCryptoServiceProvider tripleDES = new TripleDESCryptoServiceProvider();  
  28.          tripleDES.Key = UTF8Encoding.UTF8.GetBytes(key);  
  29.          tripleDES.Mode = CipherMode.ECB;  
  30.          tripleDES.Padding = PaddingMode.PKCS7;  
  31.          ICryptoTransform cTransform = tripleDES.CreateEncryptor();  
  32.          byte[] resultArray = cTransform.TransformFinalBlock(inputArray, 0, inputArray.Length);  
  33.          tripleDES.Clear();  
  34.          return Convert.ToBase64String(resultArray, 0, resultArray.Length);  
  35.       }  
  36.       public static string Decrypt(string input, string key)  
  37.       {  
  38.          byte[] inputArray = Convert.FromBase64String(input);  
  39.          TripleDESCryptoServiceProvider tripleDES = new TripleDESCryptoServiceProvider();  
  40.          tripleDES.Key = UTF8Encoding.UTF8.GetBytes(key);  
  41.          tripleDES.Mode = CipherMode.ECB;  
  42.          tripleDES.Padding = PaddingMode.PKCS7;  
  43.          ICryptoTransform cTransform = tripleDES.CreateDecryptor();  
  44.          byte[] resultArray = cTransform.TransformFinalBlock(inputArray, 0, inputArray.Length);  
  45.          tripleDES.Clear();  
  46.          return UTF8Encoding.UTF8.GetString(resultArray);  
  47.       }  
  48.       #endregion  
  49.       private void button2_Click(object sender, EventArgs e)  
  50.       {  
  51.          textBox3.Text = Decrypt(textBox2.Text, "sanketshinde@12345678912");  
  52.       }  
  53.    }  
  54. }