.net下几种实现MD5算法的途径

		/// <summary>
		/// 获取MD5得值,转换成BASE64
		/// </summary>
		/// <param name="Sourcein"></param>
		/// <returns></returns>
		public static string MD5(string Sourcein)
{
System.Security.Cryptography.MD5CryptoServiceProvider MD5CSP = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] MD5Source = System.Text.Encoding.UTF8.GetBytes(Sourcein);
byte[] MD5Out = MD5CSP.ComputeHash(MD5Source);

return Convert.ToBase64String(MD5Out);
}


/// <summary> /// 获取MD5得值,没有转换成Base64的 /// </summary> /// <param name="sDataIn">需要加密的字符串</param> /// <param name="move">偏移量</param> /// <returns>sDataIn加密后的字符串</returns> public string GetMD5(string sDataIn, string move)
{
System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[]byt, bytHash;
byt = System.Text.Encoding.UTF8.GetBytes(move + sDataIn);
bytHash = md5.ComputeHash(byt);
md5.Clear();
string sTemp = "";
for (int i = 0; i < bytHash.Length; i ++ )
{
sTemp += bytHash[i].ToString("x").PadLeft(2, '0');
}
return sTemp;
}

/// <summary> /// ASP.net下获取Md5 /// </summary> /// <param name="source"></param> /// <returns></returns> public string MD5AspDotNet(string source)
{
return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(source, "MD5");
}
 
以上第一种方法获得的结果和后面几种方法的结果不一样,但是效果是一样的,如果你的程序是从ASP转过来的话,推荐使用第2种或第3种方法

扩展方法:
    static class StringExtensions
    {
        
public static string Nl2Br(this string s)
        {
            
return s.Replace("\r\n", "<br />").Replace("\n", "<br />");
        }

        
public static string MD5(this string s)
        {
            MD5CryptoServiceProvider provider;
            provider 
= new MD5CryptoServiceProvider();
            byte
[] bytes = Encoding.UTF8.GetBytes(s);
            StringBuilder builder 
= new StringBuilder();

            bytes 
= provider.ComputeHash(bytes);
           
            foreach (byte b 
in bytes)
                builder.Append(b.ToString("x2").ToLower());
           
            
return builder.ToString();
        }
    }

posted @ 2008-03-27 19:04  代码乱了  阅读(6408)  评论(0编辑  收藏  举报