I would like to share some simple functions which can encrypt and decrypt string
s. These functions can be used in any of .NET Framework supporting languages.
Just declare a pass phrase in your code like a master key which allows the MD5CryptoServiceProvider
class (in the System.Security and System.Security.Cryptography
namespace) to compute a hash value for encryption/decryption. TripleDESCryptoServiceProvider
class is used to encrypt/ decrypt string
s which in turn uses 3DES (Triple Data Encryption Standard) algorithm. 3DES alogorithm uses three 64-bit long keys to (Encrypt-Decrypt-Encrypt) data.
Declare the pass phrase as below, and you can set any string
value you like:
const string passphrase = "password";
For example, "password" is the key I used here.
Now, you just have to use the Encrypt/Decrypt functions below in your class to encrypt and decrypt any string
.
Below are the functions:
Encrypt function:
public static string EncryptData(string Message)
{
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 function:
public static string DecryptString(string Message)
{
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);
}
Hope this helps someone save time while coding.
Happy coding!!!