Sunday, February 8, 2009

Triple DES Encrypt/decrypt extension method

I wanted to have a simple encryption method so that I could convert any string.
return credentials.Encrypt();


You should note that there is no constructor as it is better to initialise our key with a function call.


/// <summary>
///
The class will encrypt or decrpyt based on Triple DES algoritm
/// </summary>
public static class EncryptionService
{
static byte[] _encryptionKey = InitialiseKey();

/// <summary>
///
Initialises the key.
/// </summary>
/// <returns></returns>
private static byte[] InitialiseKey()
{
string encryptionKey = ConfigurationManager.AppSettings["EncryptionPassword"];
if (string.IsNullOrEmpty(encryptionKey))
throw new ConfigurationErrorsException(
"'EncryptionPassword' is not defined in your config file."
);

byte[] encryptionKeyBytes = ASCIIEncoding.ASCII.GetBytes(encryptionKey);

using (MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider())
{
return hashmd5.ComputeHash(encryptionKeyBytes);
}
}

/// <summary>
///
Decrypts the specified input.
/// </summary>
/// <param name="input">
The input.</param>
/// <returns></returns>
public static string Decrypt(this string input)
{
if (string.IsNullOrEmpty(input))
return string.Empty;

using (TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider())
{
des.Key = _encryptionKey;
des.Mode = CipherMode.ECB;

byte[] buff = null;
try
{
buff = Convert.FromBase64String(input);
}
catch (FormatException)
{
return string.Empty;
}

return ASCIIEncoding.ASCII.GetString(
des.CreateDecryptor().TransformFinalBlock(buff, 0, buff.Length));
}
}

/// <summary>
///
Encrypts the specified input.
/// </summary>
/// <param name="input">
The input.</param>
/// <returns></returns>
public static string Encrypt(this string input)
{
using (TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider())
{
des.Key = _encryptionKey;
des.Mode = CipherMode.ECB;

byte[] buff = ASCIIEncoding.ASCII.GetBytes(input);

return Convert.ToBase64String(
des.CreateEncryptor().TransformFinalBlock(buff, 0, buff.Length));
}
}
}

No comments: