C#获取MD5哈希字符串


 

using System.Security.Cryptography;
using System.Text;

public class MD5Helper
{
    private static MD5 md5 = MD5.Create();

    //使用utf8编码将字符串散列
    public static string GetMD5HashString(string sourceStr)
    {
        return GetMD5HashString(Encoding.UTF8,sourceStr);    
    }

    //使用指定编码将字符串散列
    public static string GetMD5HashString(Encoding encode,string sourceStr)
    {
        StringBuilder sb = new StringBuilder();

        byte[] source = md5.ComputeHash(encode.GetBytes(sourceStr));
        for (int i = 0; i < source.Length; i++)
        {
            sb.Append(source[i].ToString("x2"));
        }

        return sb.ToString();  
    }
}

上面的方法与下面的方法计算结果相同:

System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sourceStr, "MD5").ToLower()),sourceStr是要进行哈希运算的字符串,非Asp.Net应用需要添加System.Web.dll引用。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM