关于C# MD5 加密的方法

比如:我们要对字符串 "123123" 进行加密 分别调用下面方法

WEB写法:

    /// <summary>
    /// MD5加密方法一
    /// </summary>
    /// <param name="password">要加密字符串</param>
    /// <returns>加密后字符串</returns>
    public string MD5Encrypt1(string password)
    {
        string my = System.Web.Configuration.FormsAuthPasswordFormat.MD5.ToString(); //"MD5"  
        return FormsAuthentication.HashPasswordForStoringInConfigFile(password, my);       
    } 

    返回结果:4297F44B13955235245B2497399D7A93

 

    /// <summary>
    /// MD5加密方法二
    /// </summary>
    /// <param name="password">要加密字符串</param>
    /// <returns>加密后字符串</returns>
    public string MD5Encrypt2(string password)
    {      
        System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
        byte[] result = md5.ComputeHash(System.Text.Encoding.Default.GetBytes(password));
        //return BitConverter.ToString(result);
        return BitConverter.ToString(result).Replace("-", "");
    }

   //返回结果:42-97-F4-4B-13-95-52-35-24-5B-24-97-39-9D-7A-93

   返回结果:4297F44B13955235245B2497399D7A93

 

WinForm 写法:

引用:

using System.Security;
using System.Security.Principal;
using System.Security.Cryptography;

 

       /// <summary>
       /// MD5加密方法一
       /// </summary>
       /// <param name="password">要加密的字符串</param>
       /// <returns>加密后的字符串</returns>   
        public string MD5Encrypt1(string password)
        {         
            //可以用不同的编码获取Byte数组
            //Byte[] s = new UnicodeEncoding().GetBytes(password);
              Byte[] s = new UTF8Encoding().GetBytes(password);
          
            //获取Hash值
            //Byte[] result = ((HashAlgorithm)CryptoConfig.CreateFromName("MD5")).ComputeHash(s);  
              Byte[] result = MD5.Create().ComputeHash(s);
            //获取加密后的信息
            //return BitConverter.ToString(result);
            return BitConverter.ToString(result).Replace("-", "");
        }

   //返回结果:42-97-F4-4B-13-95-52-35-24-5B-24-97-39-9D-7A-93

   返回结果:4297F44B13955235245B2497399D7A93

 

        /// <summary>
        /// MD5加密方法二
        /// </summary>
        /// <param name="password">要加密的字符串</param>
        /// <returns>加密后的字符串</returns>
        public string MD5Encrypt2(string password)
        {   
            string pwd = "";          
            // 加密后是一个字节类型的数组,这里要注意编码UTF8/Unicode等的选择 
            byte[] s = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(password));
          
            // 通过使用循环,将字节类型的数组转换为字符串,此字符串是常规字符格式化所得
            for (int i = 0; i < s.Length; i++)
            {
                // 将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母,如果使用大写(X)则格式后的字符是大写字符
                //pwd = pwd + s[i].ToString("x");
                pwd = pwd + s[i].ToString("X");
            }
            return pwd;
        }

    //返回结果:4297f44b13955235245b2497399d7a93

    返回结果:4297F44B13955235245B2497399D7A93

 

 

posted @ 2010-12-01 16:28  闭着眼睛想  阅读(1318)  评论(0编辑  收藏  举报