码迷,mamicode.com
首页 > 其他好文 > 详细

MD5

时间:2014-07-22 22:49:32      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:blog   os   io   for   re   c   

using (var md5 = MD5.Create())
{
    using (var stream = File.OpenRead(filename))
    {
        return md5.ComputeHash(stream);
    }
}
or
public static string GetMD5HashFromFile(string filename)
{
    using (var md5 = new MD5CryptoServiceProvider())
    {
        var buffer = md5.ComputeHash(File.ReadAllBytes(filename));
        var sb = new StringBuilder();
        for (int i = 0; i < buffer.Length; i++)
        {
            sb.Append(buffer[i].ToString("x2"));
        }
        return sb.ToString();
    }
}

 


(I believe that actually the MD5 implementation used doesn‘t need to be disposed, but I‘d probably still do so anyway.)

How you compare the results afterwards is up to you; you can convert the byte array to base64 for example, or compare the bytes directly. (Just be aware that arrays don‘t override Equals. Using base64 is simpler to get right, but slightly less efficient if you‘re really only interested in comparing the hashes.)

 

If you want the "standard" looking md5, you can do: return

BitConverter.ToString(md5.ComputeHash(stream)).Replace("-","").ToLower();

 

判断一字符串是否是MD5字符串

Regex: [0-9a-f]{32}

MD5,布布扣,bubuko.com

MD5

标签:blog   os   io   for   re   c   

原文地址:http://www.cnblogs.com/zeroone/p/3861161.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!