Simple C#.Net Encryption and Decryption for String

There are many ways is there to encrypt and decrypt the data in c#.Net. In this post we have simple sample code to implement the cryptography algorithm in C#.Net to encrypt and decrypt information, either passwords or connection strings. This code uses the System.Security.Cryptography namespace to do the encryption and decryption. Please find the code below.

Namespace

using System.Security.Cryptography;

Calling Encrypt String

string Password = “hidden”;
string EncryptedString = EncryptString(“Your Original Value”, Password);

Calling Decrypt String

string Password = “hidden”;
string originalstring= DecryptString(EncryptedString , Password);

Encrypt String Method

public static string EncryptString(string Message, string Passphrase)
{
byte[] Results;
System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();

MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));

TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();

TDESAlgorithm.Key = TDESKey;
TDESAlgorithm.Mode = CipherMode.ECB;
TDESAlgorithm.Padding = PaddingMode.PKCS7;

byte[] DataToEncrypt = UTF8.GetBytes(Message);

try
{
ICryptoTransform Encryptor = TDESAlgorithm.CreateEncryptor();
Results = Encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length);
}
finally
{
TDESAlgorithm.Clear();
HashProvider.Clear();
}
return Convert.ToBase64String(Results);
}

Decrypt String Method

public static string DecryptString(string Message, string Passphrase)
{
byte[] Results;
System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();

MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));

TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();

TDESAlgorithm.Key = TDESKey;
TDESAlgorithm.Mode = CipherMode.ECB;
TDESAlgorithm.Padding = PaddingMode.PKCS7;

byte[] DataToDecrypt = Convert.FromBase64String(Message);

try
{
ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor();
Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length);
}
finally
{
TDESAlgorithm.Clear();
HashProvider.Clear();
}

return UTF8.GetString(Results);
}

Leave a Reply

Your email address will not be published. Required fields are marked *

(Required)

Proudly powered by WordPress   Premium Style Theme by www.gopiplus.com