C#.NET Encryption Technology TripleDES

How to TripleDES encrypt decrypt data? – Part Two

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.

private string GetXmlKey(string xmlPath)
{
string hashKey = “”;
try
{
XDocument doc = XDocument.Load(xmlPath);
hashKey = doc.Descendants(“key”).ElementAt(0).Value;
}
catch(SystemException)
{
throw new Exception(“Xml Document Load Error”);
}
      return hashKey;
}



Include the below method to create the TripleDES object from Hashkey.

private TripleDES CreateDES(string 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.

public string EncryptData(string Data)
{
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 EncryptData = my3DES.EncryptData(“Your Data”);
string DecryptData = my3DES.DecryptData(EncryptData);



Usefull Links – New Terms
How DES works?
MD5 – Wikipedia
Cryptographic hash function – Wikipedia

Spread the love
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments