This post has reference to part one of this Article.
Inside our “TripleDESCrypt“ class, lets implement another method to read the MD5 HashKey generated from the Secret Key from the User. This method will load the TripleDESKey.xml file and returns the HashKey in String format.
{
string hashKey = “”;
try
{
XDocument doc = XDocument.Load(xmlPath);
hashKey = doc.Descendants(“key”).ElementAt(0).Value;
}
catch(SystemException)
{
throw new Exception(“Xml Document Load Error”);
}
}
Include the below method to create the TripleDES object from Hashkey.
{
TripleDES des = new TripleDESCryptoServiceProvider();
des.Key = Convert.FromBase64String(hashKey);
des.IV = new byte[des.BlockSize / 8];
return des;
}
Include the following two methods inside the “TripleDESCrypt“ class, these two methods will be used to Encrypt and Decrypt user input data respectively.
{
string key = GetXmlKey(myPath);
TripleDES des = CreateDES(key);
ICryptoTransform ct = des.CreateEncryptor();
byte[] input = Encoding.Unicode.GetBytes(Data);
byte[] output = ct.TransformFinalBlock(input, 0, input.Length);
return Convert.ToBase64String(output);
}
public string DecryptData(string Data)
{
string key = GetXmlKey(myPath);
byte[] input = Convert.FromBase64String(Data);
TripleDES des = CreateDES(key);
ICryptoTransform ct = des.CreateDecryptor();
byte[] output = ct.TransformFinalBlock(input, 0, input.Length);
return Encoding.Unicode.GetString(output);
}
Now, inside the Aspx page, add the below two lines of code to test the Encryption and Decryption using TripleDES.
string DecryptData = my3DES.DecryptData(EncryptData);
Usefull Links – New Terms
How DES works?
MD5 – Wikipedia
Cryptographic hash function – Wikipedia