.Net加密与解密

正文:

      1.MD5加密实现方式一:

        /// <summary>
        /// 获取MD5密码
        /// </summary>
        /// <returns></returns>
        public static string GetMd5(string pwd)
        {
            string md5Pwd = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(pwd, "md5");
            return md5Pwd;
        }

       2.MD5加密实现方式二:

        /// <summary>
        /// 使用自带的类进行MD5加密
        /// </summary>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public static string GetMd5(string pwd)
        {
            MD5 md5 = MD5.Create(); //创建用于MD5加密的MD5对象
            byte[] ms=Encoding.Default.GetBytes(pwd);
            byte[] newms=md5.ComputeHash(ms);//对根据用户密码生成的byte类型的数据进行hash散列算法,返回了一个新的byte数组
            StringBuilder sb = new StringBuilder();
            foreach (byte item in newms)
            {
                //x:小写的16进制数  X:大写的16进制数  后面的数值是指转换后的16进制的位数
                sb.Append(item.ToString("X2"));
            }
            return sb.ToString();
        }

       Note:只有加密没有解密,单向的;

       3.DES加密
        /// <summary>
        /// 加密数据
        /// </summary>
        /// <param name="Text">加密数据</param>
        /// <param name="sKey">根据key加密</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));
            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();
        }
        4.DES解密:
        /// <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());
        }
       5.  3des加密
        /// <summary>
        /// 3des加密字符串
        /// </summary>
        /// <param name="text">要加密的字符串</param>
        /// <param name="key">密钥</param>
        /// <returns>加密后并经base64编码的字符串</returns>
        /// <remarks>静态方法,采用默认ascii编码</remarks>
        public static string Encrypt(string text, string key)
        {
            TripleDESCryptoServiceProvider DES = new
                TripleDESCryptoServiceProvider();
            MD5CryptoServiceProvider hashMD5 = new MD5CryptoServiceProvider();

            //3des密匙
            DES.Key = hashMD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(key));
            //模式为电子密码块模式
            DES.Mode = CipherMode.ECB;

            //创建Encryptor对象
            ICryptoTransform DESEncrypt = DES.CreateEncryptor();
            //将需要加密的字符串转化为字节数组
            byte[] Buffer = ASCIIEncoding.UTF8.GetBytes(text);
            //通过加密对象的TransformFinalBlock()进行加密
            //转化为Base64字符串返回
            return Convert.ToBase64String(DESEncrypt.TransformFinalBlock
                (Buffer, 0, Buffer.Length));
        }//end method

       6.3des解密
        /// <summary>
        /// 3des解密字符串
        /// </summary>
        /// <param name="text">要解密的字符串</param>
        /// <param name="key">密钥</param>
        /// <returns>解密后的字符串</returns>
        /// <exception cref="">密钥错误</exception>
        /// <remarks>静态方法,采用默认ascii编码</remarks>
        public static string Decrypt(string text, string key)
        {
            TripleDESCryptoServiceProvider DES = new
                TripleDESCryptoServiceProvider();
            MD5CryptoServiceProvider hashMD5 = new MD5CryptoServiceProvider();
            //密匙
            DES.Key = hashMD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(key));
            //模式
            DES.Mode = CipherMode.ECB;
            //创建Encryptor对象
            ICryptoTransform DESDecrypt = DES.CreateDecryptor();

            string result = "";
            try
            {
                //将加密后的字符串转化为byte数组
                byte[] Buffer = Convert.FromBase64String(text);
                //TransformFinalBlock()返回解密后的byte数组
                //通过UTF8编码返回字符串
                result = ASCIIEncoding.UTF8.GetString(DESDecrypt.TransformFinalBlock
                    (Buffer, 0, Buffer.Length));
            }
            catch (Exception e)
            {
                return text;
               // throw (new Exception("Invalid Key or input string is not a valid base64 string", e));
            }

            return result;
        }//end method

 

posted on 2015-09-06 01:06  巴夫巴夫  阅读(169)  评论(0编辑  收藏  举报