2012-08-01 39 views
1

當我加密字符串時收到錯誤信息,但是,當我嘗試解密字符串時收到錯誤消息,它說Input.Length無效。有任何想法嗎?C#TripleDES解密時輸入長度不正確

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

不需要'new UTF8Encoding()','Encoding.UTF8'已經可用。 – spender 2012-08-01 16:08:25

回答

3

加密過程返回的字節不是UTF8,但是您正在對待它們。如果您想要對加密數據進行文本表示,則只需將任意字節轉換爲UTF8即可。

Skeet的回答here應該設置你的方式。