I’m working on a mvc application over .Net, to secure my sensitive information such as info in web.config I’ve got two functions that encrypts and decrypts information using Triple DES, however I’m new to this and succeeded to reach till here by the help of a friend and asking few question over here.
The point where I’m currently stuck is how can I add TDES IV (Initialization Vector)
at the end of the encrypted string and how also retrieve it again while decrypting? I mean how would you identify in an encrypted info that from here the IV (Initialization Vector)
stars?
Kindly help.
public static string Encrypt(string Message)
{
byte[] iv;
byte[] Results;
System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(GetSHA256String()));
TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();
TDESAlgorithm.Key = TDESKey;
TDESAlgorithm.Mode = CipherMode.ECB;
TDESAlgorithm.Padding = PaddingMode.PKCS7;
// Capture the randomly generated IV
iv = TDESAlgorithm.IV;
byte[] DataToEncrypt = UTF8.GetBytes(Message);
try
{
ICryptoTransform Encryptor = TDESAlgorithm.CreateEncryptor();
Results = Encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length);
//var lnght=Results.GetLength(0);
//System.Buffer.BlockCopy(iv, 0, Results, lnght + 1, iv.Length()); //HOW?
}
finally
{
TDESAlgorithm.Clear();
HashProvider.Clear();
}
return Convert.ToBase64String(Results);
//return Encoding.UTF8.GetString(Results);
}
public static string Decrypt(string Message)
{
byte[] Results;
System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(GetSHA256String()));
TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();
TDESAlgorithm.Key = TDESKey;
// Apply the same IV used during encryption
//TDESAlgorithm.IV = iv; // HOW?
TDESAlgorithm.Mode = CipherMode.ECB;
TDESAlgorithm.Padding = PaddingMode.PKCS7;
try
{
byte[] DataToDecrypt = Convert.FromBase64String(Message);
//byte[] DataToDecrypt = UTF8.GetBytes(Message);
//byte[] DataToDecrypt = Encoding.UTF8.GetBytes(Message);
ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor();
Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length); // << ERROR is here.
}
finally
{
TDESAlgorithm.Clear();
HashProvider.Clear();
}
return UTF8.GetString(Results);
}
…
…
…