Y_NX
Y_NX

Reputation: 11

C# TripleDES incorrect Input Length when decrypting

I get no error when I encrypt a string but, I get an error when I try to decrypt the string, it says that the Input.Length is invalid. Any ideas?

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;
        }
    }

Upvotes: 1

Views: 1625

Answers (1)

spender
spender

Reputation: 120450

The bytes returned by the encryption process are not UTF8, but you're treating them as such. If you want a textual representation of the encrypted data, you'll need to do a little more than simply converting arbitrary bytes to UTF8.

Skeet's answer here should set you on your way.

Upvotes: 3

Related Questions