How to Encrypting and Decripting values using Security Key

This junk of code is used to Encrypt and Decrypt the values depending on a key called Security Key. Which is saved in the web.config file or in database.


public sealed class EncryptCard
{
private EncryptCard()
{
}


public static string Encrypt(string toEncrypt, bool useHashing)
{
if (!string.IsNullOrEmpty(toEncrypt))
{
byte[] keyArray;
byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);

AppSettingsReader settingsReader = new AppSettingsReader();


string key = (string)settingsReader.GetValue("SecurityKey", typeof(String));
if (useHashing)
{
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));

hashmd5.Clear();
}
else
keyArray = UTF8Encoding.UTF8.GetBytes(key);

TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();

tdes.Key = keyArray;
tdes.Mode = CipherMode.ECB;


tdes.Padding = PaddingMode.PKCS7;

ICryptoTransform cTransform = tdes.CreateEncryptor();

byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

tdes.Clear();

return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
else
{
return toEncrypt = null;
}
}

Decrypting above Encrypted value.
public static string Decrypt(string decryptValue, bool useHashing)
{
if (!string.IsNullOrEmpty(decryptValue))
{
byte[] keyArray;


byte[] toEncryptArray = Convert.FromBase64String(decryptValue);

System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();

string key = (string)settingsReader.GetValue("SecurityKey", typeof(String));

if (useHashing)
{

MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));


hashmd5.Clear();
}
else
{

keyArray = UTF8Encoding.UTF8.GetBytes(key);
}

TripleDESCryptoServiceProvider tdesProvider = new TripleDESCryptoServiceProvider();

tdesProvider.Key = keyArray;

tdesProvider.Mode = CipherMode.ECB;

tdesProvider.Padding = PaddingMode.PKCS7;

ICryptoTransform cTransform = tdesProvider.CreateDecryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

tdesProvider.Clear();

return UTF8Encoding.UTF8.GetString(resultArray);
}
else
{
return decryptValue = null;
}
}
}

Here. I added the securityKey in web.config file
appSettings>

<add key ="SecurityKey" value="DOTNETMATRIX"/>
</appSettings>

No comments: