兔八哥极品软件园    运行: 4515天 | 文章:640 篇 | 评论:577 条 | 碎语:1条

.NET自带类完美计算MD5

作者:admin 发布于:2012-8-14 8:23 Tuesday 分类:.NET


using System;
using System.Collections.Generic;
using System.Text;

using System.Security.Cryptography;
using System.IO;

namespace RabbitExt
{
    public class Md5Ext
    {
        private static MD5 md5 = new MD5CryptoServiceProvider();

        public Md5Ext()
        {
        }

        private static string MD5ByteToStr(byte[] b)
        {
            string result = "";
            for (int i = 0; i < b.Length; i++)
            {
                result += b[i].ToString("X2");
            }
            return result;
        }

        public static string CalcFileMD5(string fileName)
        {
            Stream stream = File.OpenRead(fileName);
            return CalcStreamMD5(stream);
        }

        public static string CalcStreamMD5(Stream stream)
        {
            byte[] md5Hash = md5.ComputeHash(stream);
            return MD5ByteToStr(md5Hash);
        }

        /// <summary>
        /// 注意传进来的byte[]编码
        /// </summary>
        /// <param name="b"></param>
        /// <returns></returns>
        public static string CalcByteMD5(byte[] b)
        {
            byte[] md5Hash = md5.ComputeHash(b);
            return MD5ByteToStr(md5Hash);
        }

        public static string CalcStringMD5(string str)
        {
            byte[] source = System.Text.Encoding.Default.GetBytes(str);
            byte[] md5Hash = md5.ComputeHash(source);
            return MD5ByteToStr(md5Hash);
        }
    }
}

标签: MD5


Powered by 兔八哥极品软件 苏ICP备12049267号 sitemap