C#Triple-Des长度不正确

时间:2014-04-27 07:16:45

标签: c# encryption tripledes

我正在尝试使用内置3Des的C#为3DES创建加密/解密代码。 我正在配置它:

    this.tDes = new TripleDESCryptoServiceProvider ();
    this.tDes.Key = new byte[]{97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112};
    this.tDes.IV = new byte[8];
    this.tDes.Mode = CipherMode.CBC;

这是我的decript功能:

    public string Decrypt(string CipherText)
    {
        byte[] cipherData = System.Text.Encoding.UTF8.GetBytes(CipherText);
        MemoryStream ms = new MemoryStream();
        CryptoStream cs = new CryptoStream(ms, this.tDes.CreateDecryptor(), CryptoStreamMode.Write);
        cs.Write(cipherData, 0, cipherData.Length);
        cs.FlushFinalBlock();
        byte[] ClearBytes = ms.ToArray();
        ms.Close();
        cs.Close();
        string decriptedData = Convert.ToBase64String(ClearBytes);
        return decriptedData;
    }

这是我的加密功能:

public string Encrypt(string InputText)
{
    byte[] clearData = System.Text.Encoding.UTF8.GetBytes(InputText);
    MemoryStream ms = new MemoryStream();
    CryptoStream cs = new CryptoStream(ms, this.tDes.CreateEncryptor(), CryptoStreamMode.Write);
    cs.Write(clearData, 0, clearData.Length);
    cs.FlushFinalBlock();
    byte[] CipherBytes = ms.ToArray();
    ms.Close();
    cs.Close();
string EncryptedData = Convert.ToBase64String(CipherBytes);
    return EncryptedData;
}

但是当尝试解密它时,C#会在“cs.FlushFinalBlock();”行中抛出错误。说不正确的长度。 什么应该是正确的尺寸? 有什么问题?

1 个答案:

答案 0 :(得分:0)

您需要在解密之前解码base 64(因此将其分配给cipherData)。然后应使用UTF8对clearBytes进行解码,并将其分配给decriptedData