Well most of the beginner and intermediate programmers like to play with cryptography. This is the part that took me to some trouble in my life. A good encryption and decryption code is easily findable in the Internet .The ClassEncryptor class holds the two static methods, Encrypt and Decrypt. The reason I put them to a separate file was because it is the best practice as far as I know and most importantly, other blocks can access these methods easily.Both Method works on the basis of Base64 Encoding Mechanism.
using System;
using System.Security.Cryptography;
using System.Text;
using System.IO;
namespace SecurityPart.Security.Cryptography {
//////////////////////////////
///Description:Class Provides methods for encrypting and decrypting clear texts.
///Created By :Ajeet Mishra
///Date:14Sept2015
//////////////////////////////
public static class ClassEncryptor {
/// Encrypts a clear text using specified password and salt.
public static string Encrypt(string clearText, string password, byte[] salt) {
byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
PasswordDeriveBytes pdb = new PasswordDeriveBytes(password, salt);
MemoryStream ms = new MemoryStream();
Rijndael alg = Rijndael.Create();
alg.Key = pdb.GetBytes(32);
alg.IV = pdb.GetBytes(16);
CryptoStream cs = new CryptoStream(ms, alg.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
byte[] EncryptedData = ms.ToArray();
return Convert.ToBase64String(EncryptedData);
}
/// Decrypts an encrypted text using specified password and salt.
public static string Decrypt(string cipherText, string password,
byte[] salt) {
byte[] cipherBytes = Convert.FromBase64String(cipherText);
PasswordDeriveBytes pdb = new PasswordDeriveBytes(password, salt);
MemoryStream ms = new MemoryStream();
Rijndael alg = Rijndael.Create();
alg.Key = pdb.GetBytes(32);
alg.IV = pdb.GetBytes(16);
CryptoStream cs = new CryptoStream(ms, alg.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(cipherBytes, 0, cipherBytes.Length);
cs.Close();
byte[] DecryptedData = ms.ToArray();
return Encoding.Unicode.GetString(DecryptedData);
}
}
}