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.
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Windows.Forms;
- using System.Security.Cryptography;
- using System.IO;
- namespace EncryptionDeMO
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
- private void button1_Click(object sender, EventArgs e)
- {
- textBox2.Text = Encrypt(textBox1.Text, "sanketshinde@12345678912");
- }
- #region Encrypt and Decrypt code
- public string Encrypt(string input, string key)
- {
- byte[] inputArray = UTF8Encoding.UTF8.GetBytes(input);
- TripleDESCryptoServiceProvider tripleDES = new TripleDESCryptoServiceProvider();
- tripleDES.Key = UTF8Encoding.UTF8.GetBytes(key);
- tripleDES.Mode = CipherMode.ECB;
- tripleDES.Padding = PaddingMode.PKCS7;
- ICryptoTransform cTransform = tripleDES.CreateEncryptor();
- byte[] resultArray = cTransform.TransformFinalBlock(inputArray, 0, inputArray.Length);
- tripleDES.Clear();
- return Convert.ToBase64String(resultArray, 0, resultArray.Length);
- }
- public static string Decrypt(string input, string key)
- {
- byte[] inputArray = Convert.FromBase64String(input);
- TripleDESCryptoServiceProvider tripleDES = new TripleDESCryptoServiceProvider();
- tripleDES.Key = UTF8Encoding.UTF8.GetBytes(key);
- tripleDES.Mode = CipherMode.ECB;
- tripleDES.Padding = PaddingMode.PKCS7;
- ICryptoTransform cTransform = tripleDES.CreateDecryptor();
- byte[] resultArray = cTransform.TransformFinalBlock(inputArray, 0, inputArray.Length);
- tripleDES.Clear();
- return UTF8Encoding.UTF8.GetString(resultArray);
- }
- #endregion
- private void button2_Click(object sender, EventArgs e)
- {
- textBox3.Text = Decrypt(textBox2.Text, "sanketshinde@12345678912");
- }
- }
- }