TripleDes类解密问题

时间:2012-08-06 06:38:46

标签: c# encryption cryptography

我创建了一个类似的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")));
    }

加密方法运行正常,但解密方法就是问题,因为当我使用decrypt时,它会生成一些随机数据,同时输出:Hey TEST DATA。

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

这是你的问题:

return ASCIIEncoding.ASCII.GetString(enc);
...
byte[] data = Encoding.ASCII.GetBytes(Data);

您将加密数据视为ASCII文本。不是。你丢失了数据。

要在不丢失文本的情况下表示任意二进制数据,您几乎应该始终使用Base64:

return Convert.ToBase64String(enc);
...
byte[] data = Convert.FromBase64String(Data);

此外,我建议使用ASCII以外的东西将键/ iv文本转换为字节 - 并遵循参数的.NET命名约定。

相关问题