日期:2014-05-17  浏览次数:20673 次

加密解密问题
C# code


        /// <summary> 
        /// 加密数据 
        /// </summary> 
        /// <param name="Text"></param> 
        /// <param name="sKey"></param> 
        /// <returns></returns> 
        public static string Encrypt(string Text,string sKey) 
        { 
            DESCryptoServiceProvider des = new DESCryptoServiceProvider(); 
            byte[] inputByteArray; 
            inputByteArray=Encoding.Default.GetBytes(Text);
            des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8)); //Please add references (System.Web)
            des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8)); 
            System.IO.MemoryStream ms=new System.IO.MemoryStream(); 
            CryptoStream cs=new CryptoStream(ms,des.CreateEncryptor(),CryptoStreamMode.Write); 
            cs.Write(inputByteArray,0,inputByteArray.Length); 
            cs.FlushFinalBlock(); 
            StringBuilder ret=new StringBuilder(); 
            foreach( byte b in ms.ToArray()) 
            { 
                ret.AppendFormat("{0:X2}",b); 
            } 
            return ret.ToString(); 
        } 





C# code

        /// <summary> 
        /// 解密数据 
        /// </summary> 
        /// <param name="Text"></param> 
        /// <param name="sKey"></param> 
        /// <returns></returns> 
        public static string Decrypt(string Text,string sKey) 
        { 
            DESCryptoServiceProvider des = new DESCryptoServiceProvider(); 
            int len; 
            len=Text.Length/2; 
            byte[] inputByteArray = new byte[len]; 
            int x,i; 
            for(x=0;x<len;x++) 
            { 
                i = Convert.ToInt32(Text.Substring(x * 2, 2), 16); 
                inputByteArray[x]=(byte)i; 
            } 
            des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8)); 
            des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8)); 
            System.IO.MemoryStream ms=new System.IO.MemoryStream(); 
            CryptoStream cs=new CryptoStream(ms,des.CreateDecryptor(),CryptoStreamMode.Write); 
            cs.Write(inputByteArray,0,inputByteArray.Length); 
            cs.FlushFinalBlock(); 
            return Encoding.Default.GetString(ms.ToArray()); 
        } 




加密没问题 解密时候为什么提示 
要解密的数据的长度无效。

错误行 cs.FlushFinalBlock();

有人遇见过吗 谢谢了

------解决方案--------------------
密文怎么出来是 string?直接byte。。。
或者 Encoding.Unicode.GetString()

试试。。。
------解决方案--------------------
我加密是将整个程序加密的,用的xencode 即加密又加壳,很方便,但是有升级程序或者调用webservice会有点问题,不过我已经解决了,加密一段文字的我也弄过,没有出现你那样的问题啊。