Before we check C# encrypt password & decrypt code example using triple DES algorithm in console application, let's understand what is Encryption & Decryption means.
Table of Contents
Encryption is the process of translating plain text data (plaintext) into something that appears to be random and meaningless (ciphertext).It is used to transform a data into some un-readable form so that authenticated person only can read/access the data. It requires some secret information to transform the plain text to cipher text; it is usually referred as key.
Decryption is the process of converting ciphertext back to plaintext. To encrypt more than a small amount of data, symmetric encryption is used.
There are many modern cryptographic methods used for encryption and decryption and it is classified in to two classes of key based algorithms.
- Symmetric Algorithm
- Same key is used for both Encryption and Decryption. The key will be kept as secret.
- Symmetric Ciphers is divided into Stream and Block Ciphers.
- Stream Ciphers – It encrypts a single bit of plain text at a time.
- Block Ciphers – It takes number of bits and encrypts them as a single unit.
- Asymmetric Algorithm
- Different key is used for Encryption and Decryption. It is also called as public Key algorithm.
- Encryption key is public and the Decryption key will be kept as secret.
- By using this asymmetric algorithm, anyone can encrypt the message by using encryption key but the message can be decrypted only by using decryption key.
- Hybrid Encryption – Symmetric and Asymmetric algorithm are used together and it is called as Hybrid Encryption.
Symmetric Encryption Algorithm are as below
- Data Encryption Standard (DES)
- Blow Fish
- Triple DES (3DES)
- Advanced Encryption Standard (AES)
Encrypt and Decrypt string in C# example
Here is the C# Triple DES algorithm encryption and decryption example
using System;
using System.Security.Cryptography;
using System.Text;
namespace EncryptDecryptPasswordCsharp
{
class Program
{
static void Main(string[] args)
{
var text = "This is my password to protect";
var encryptedText = EncryptPlainTextToCipherText(text);
var decryptedText = DecryptCipherTextToPlainText(encryptedText);
Console.WriteLine("Passed Text = " + text);
Console.WriteLine("EncryptedText = " + encryptedText);
Console.WriteLine("DecryptedText = " + decryptedText);
Console.ReadLine();
}
//This security key should be very complex and Random for encrypting the text. This playing vital role in encrypting the text.
private const string SecurityKey = "ComplexKeyHere_12121";
//This method is used to convert the plain text to Encrypted/Un-Readable Text format.
public static string EncryptPlainTextToCipherText(string PlainText)
{
// Getting the bytes of Input String.
byte[] toEncryptedArray = UTF8Encoding.UTF8.GetBytes(PlainText);
MD5CryptoServiceProvider objMD5CryptoService = new MD5CryptoServiceProvider();
//Gettting the bytes from the Security Key and Passing it to compute the Corresponding Hash Value.
byte[] securityKeyArray = objMD5CryptoService.ComputeHash(UTF8Encoding.UTF8.GetBytes(SecurityKey));
//De-allocatinng the memory after doing the Job.
objMD5CryptoService.Clear();
var objTripleDESCryptoService = new TripleDESCryptoServiceProvider();
//Assigning the Security key to the TripleDES Service Provider.
objTripleDESCryptoService.Key = securityKeyArray;
//Mode of the Crypto service is Electronic Code Book.
objTripleDESCryptoService.Mode = CipherMode.ECB;
//Padding Mode is PKCS7 if there is any extra byte is added.
objTripleDESCryptoService.Padding = PaddingMode.PKCS7;
var objCrytpoTransform = objTripleDESCryptoService.CreateEncryptor();
//Transform the bytes array to resultArray
byte[] resultArray = objCrytpoTransform.TransformFinalBlock(toEncryptedArray, 0, toEncryptedArray.Length);
objTripleDESCryptoService.Clear();
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
//This method is used to convert the Encrypted/Un-Readable Text back to readable format.
public static string DecryptCipherTextToPlainText(string CipherText)
{
byte[] toEncryptArray = Convert.FromBase64String(CipherText);
MD5CryptoServiceProvider objMD5CryptoService = new MD5CryptoServiceProvider();
//Gettting the bytes from the Security Key and Passing it to compute the Corresponding Hash Value.
byte[] securityKeyArray = objMD5CryptoService.ComputeHash(UTF8Encoding.UTF8.GetBytes(SecurityKey));
objMD5CryptoService.Clear();
var objTripleDESCryptoService = new TripleDESCryptoServiceProvider();
//Assigning the Security key to the TripleDES Service Provider.
objTripleDESCryptoService.Key = securityKeyArray;
//Mode of the Crypto service is Electronic Code Book.
objTripleDESCryptoService.Mode = CipherMode.ECB;
//Padding Mode is PKCS7 if there is any extra byte is added.
objTripleDESCryptoService.Padding = PaddingMode.PKCS7;
var objCrytpoTransform = objTripleDESCryptoService.CreateDecryptor();
//Transform the bytes array to resultArray
byte[] resultArray = objCrytpoTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
objTripleDESCryptoService.Clear();
//Convert and return the decrypted data/byte into string format.
return UTF8Encoding.UTF8.GetString(resultArray);
}
}
}
Output:
Passed Text = This is my password to protect
EncryptedText = m7YCTb0Q6yCUmAFVYg+hYuauJkvxmrJtXGZfzSUk6/A=
DecryptedText = This is my password to protect
That's it we are done with the above method.
C# Encrypt Password using MD5 example
MD5 is also considered one of the best ways to save password, but in this method we would not be able to decrypt it, Md5() is one way function,means you can Encrypt Something but after that you can not decrypt it, so using it means when we save Encrypted string or password in database we save encryption key also somewhere in database or in Code.
So when user enters password in Login page then we re-calculate MD5 & we need to match the newly created MD5 encrypted string with the saved one in database, it if matches , user has entered correct password show home-page to it.
Here is the sample C# code to create MD5 encrypted string
public static string CalculateMD5Hash(string input)
{
// To calculate MD5 hash from an input string
MD5 md5 = MD5.Create();
byte[] inputBytes =Encoding.ASCII.GetBytes(input);
byte[] hash = md5.ComputeHash(inputBytes);
// convert byte array to hex string
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hash.Length; i++)
{
//to make hex string use lower case instead of uppercase add parameter "X2"
sb.Append(hash[i].ToString("X2"));
}
return sb.ToString();
}
After adding the above Code in our already created console app, here the output:
Passed Text = This is my password to protect
EncryptedText = m7YCTb0Q6yCUmAFVYg+hYuauJkvxmrJtXGZfzSUk6/A=
DecryptedText = This is my password to protect
MD5 Encrypted string: 81653AB42A6B695D1583622DB63F8661
Which algorithm to use for encrypting password?
After checking above algorithms, you may think which one we should use for password encryption.
MD5 and SHA are not encryption algorithms, and it is important that you understand the difference. They are digest or signature algorithms; they take an input string of arbitrary size and produce a fixed-length result. Each MD5 result maps to multiple different input strings. These are strictly one-way operations -- there is no way to "undo" an MD5 or SHA hash to find the original text.
If you want a digest algorithm, then MD5 is OK and SHA is better. If you really do want encryption that can be decrypted, then you need something like AES or RSA.
You may also like to read:
vikas_jk
It is already here in the article, C# console application complete code, check sample code here
Thanks.
Vinnu
Please check Vikas's comment it is in article, thanks.