解密时,C#将不正确的输入长度增加三倍

解密时,C#将不正确的输入长度增加三倍,c#,encryption,3des,tripledes,C#,Encryption,3des,Tripledes,加密字符串时没有错误,但是, 当我尝试解密字符串时,出现了一个错误,它表明Input.Length无效。有什么想法吗 public class Crypt { public string Encrypt(string Key, string Input) { ICryptoTransform crypted = tran(Key).CreateEncryptor(); UTF8Encoding utf8 =

加密字符串时没有错误,但是, 当我尝试解密字符串时,出现了一个错误,它表明Input.Length无效。有什么想法吗

public class Crypt
    {
        public string Encrypt(string Key, string Input)
        {
            ICryptoTransform crypted = tran(Key).CreateEncryptor();
            UTF8Encoding utf8 = new UTF8Encoding();
            return utf8.GetString(crypted.TransformFinalBlock(utf8.GetBytes(Input), 0, Input.Length));
        }
        public string Decrypt(string Key, string Input)
        {
            ICryptoTransform crypted = tran(Key).CreateDecryptor();
            UTF8Encoding utf8 = new UTF8Encoding();
            return utf8.GetString(crypted.TransformFinalBlock(utf8.GetBytes(Input), 0, Input.Length));
        }
        private TripleDESCryptoServiceProvider tran(string Key)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            UTF8Encoding utf8 = new UTF8Encoding();
            TripleDESCryptoServiceProvider tDES = new TripleDESCryptoServiceProvider();
            tDES.Key = md5.ComputeHash(utf8.GetBytes(Key));
            tDES.Mode = CipherMode.ECB;
            tDES.Padding = PaddingMode.PKCS7;
            return tDES;
        }
    }

加密过程返回的字节不是UTF8,但您将它们视为UTF8。如果您想要加密数据的文本表示,您需要做的不仅仅是将任意字节转换为UTF8


Skeet的答案应该会让你上路。

不需要
新的UTF8Encoding()
编码。UTF8
已经可用。