我创建了一个这样的 TripleDes 类:
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);
}
}
我用过:
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")));
}
那么加密方法工作正常,但解密方法是问题,因为当我使用解密时它会生成一些随机数据,而它应该输出:嘿测试数据。
提前感谢您的帮助。