0

我正在尝试使用 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;

这是我的描述函数:

    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();”行中抛出一个错误。说不正确的长度。正确的尺寸应该是多少?问题是什么?

4

1 回答 1

0

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

于 2014-04-27T11:35:18.320 回答