C#加密:MD5加密
计算MD5
C# 全选
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace YESCMS.Libs
{
public class CryptoMD5
{
public static string MD5Encrypt32(string sDataIn)
{
if (String.IsNullOrEmpty(sDataIn))
return "";
var b = Encoding.UTF8.GetBytes(sDataIn);
var _md5 = new MD5CryptoServiceProvider();
byte[] output = _md5.ComputeHash(b);
string md5Str = BitConverter.ToString(output).Replace("-", "").ToLower();
_md5.Clear();
return md5Str;
}
/// <summary>
/// 通过MD5CryptoServiceProvider类中的ComputeHash方法直接传入一个FileStream类实现计算MD5
/// 操作简单,代码少,调用即可
/// </summary>
/// <param name="path">文件地址</param>
/// <returns>MD5Hash</returns>
public static string CalcFileMD5(string fileName)
{
if (!File.Exists(fileName))
throw new ArgumentException(string.Format("<{0}>, 不存在", fileName));
FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
MD5CryptoServiceProvider md5Provider = new MD5CryptoServiceProvider();
byte[] buffer = md5Provider.ComputeHash(fs);
string resule = BitConverter.ToString(buffer);
resule = resule.Replace("-", "");
md5Provider.Clear();
fs.Close();
return resule;
}
public static string CalcFileMD5(Stream stream)
{
MD5CryptoServiceProvider md5Provider = new MD5CryptoServiceProvider();
byte[] buffer = md5Provider.ComputeHash(stream);
string resule = BitConverter.ToString(buffer);
resule = resule.Replace("-", "");
md5Provider.Clear();
return resule;
}
/// <summary>
/// 通过HashAlgorithm的TransformBlock方法对流进行叠加运算获得MD5
/// 实现稍微复杂,但可使用与传输文件或接收文件时同步计算MD5值
/// 可自定义缓冲区大小,计算速度较快
/// </summary>
/// <param name="path">文件地址</param>
/// <returns>MD5Hash</returns>
public static string CalcFileMD5ByHashAlgorithm(string path)
{
if (!File.Exists(path))
throw new ArgumentException(string.Format("<{0}>, 不存在", path));
int bufferSize = 1024 * 16;//自定义缓冲区大小16K
byte[] buffer = new byte[bufferSize];
Stream inputStream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read);
HashAlgorithm hashAlgorithm = new MD5CryptoServiceProvider();
int readLength = 0;//每次读取长度
var output = new byte[bufferSize];
while ((readLength = inputStream.Read(buffer, 0, buffer.Length)) > 0)
{
//计算MD5
hashAlgorithm.TransformBlock(buffer, 0, readLength, output, 0);
}
//完成最后计算,必须调用(由于上一部循环已经完成所有运算,所以调用此方法时后面的两个参数都为0)
hashAlgorithm.TransformFinalBlock(buffer, 0, 0);
string md5 = BitConverter.ToString(hashAlgorithm.Hash);
hashAlgorithm.Clear();
inputStream.Close();
md5 = md5.Replace("-", "");
return md5;
}
}
}
版权声明:本文为YES开发框架网发布内容,转载请附上原文出处连接
post YES开发框架