I have created a TripleDes class like that :
class TripleDes_Crypto
{
// Key Lenght must be 24
string Key = string.Empty;
// IV Lenght must be 8
string IV = string.Empty;
public TripleDes_Crypto(string KEY, string IV)
{
this.Key = KEY;
this.IV = IV;
}
public string Encrypt(string Data)
{
byte[] key = Encoding.ASCII.GetBytes(Key);
byte[] iv = Encoding.ASCII.GetBytes(IV);
byte[] data = Encoding.ASCII.GetBytes(Data);
byte[] enc = new byte[0];
TripleDES tdes = TripleDES.Create();
tdes.IV = iv;
tdes.Key = key;
tdes.Mode = CipherMode.CBC;
tdes.Padding = PaddingMode.Zeros;
// encryption
ICryptoTransform ict = tdes.CreateEncryptor();
enc = ict.TransformFinalBlock(data, 0, data.Length);
return ASCIIEncoding.ASCII.GetString(enc);
}
public string Decrypt(string Data)
{
byte[] key = Encoding.ASCII.GetBytes(Key);
byte[] iv = Encoding.ASCII.GetBytes(IV);
byte[] data = Encoding.ASCII.GetBytes(Data);
byte[] dec = new byte[0];
TripleDES tdes = TripleDES.Create();
tdes.IV = iv;
tdes.Key = key;
tdes.Mode = CipherMode.CBC;
tdes.Padding = PaddingMode.Zeros;
// decryption
ICryptoTransform ict = tdes.CreateDecryptor();
dec = ict.TransformFinalBlock(data, 0, data.Length);
return ASCIIEncoding.ASCII.GetString(dec);
}
}
And i used :
private void button1_Click(object sender, EventArgs e)
{
TripleDes_Crypto tdes = new TripleDes_Crypto("passwordDR0wSS@P6660juht", "password");
File.WriteAllText(@"encrypted", tdes.Encrypt("Hey TEST DATA"));
MessageBox.Show(tdes.Decrypt(File.ReadAllText(@"encrypted")));
}
Well the encryption method works fine but the decryption method is the problem as when i use decrypt it generates some random data while it should output : Hey TEST DATA.
Thanks for help in advance.
These are your problem:
You’re treating encrypted data as if it were ASCII text. It’s not. You’re losing data.
To represent arbitrary binary data without loss in text, you should almost always use Base64:
Additionally, I’d suggest using something other than ASCII to convert key/iv text into bytes – and also follow .NET naming conventions for parameters.