using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.IO;
namespace MyMD5Checker
{
class MD5AndSHA1
{
/// <summary>
/// 用MD5散列文件
/// </summary>
/// <param name="curFileName">要散列的文件(全路径)</param>
/// <param name="flag">散列值是否使用"-"符号,为true时使用</param>
/// <returns></returns>
///
public string MD5File( string curFileName, bool flag)
{
return HashFile(curFileName, "md5",flag);
}
/// <summary>
/// 用SHA1散列文件
/// </summary>
/// <param name="curFileName">要散被列的文件(全路径)</param>
/// <param name="flag">散列值是否使用"-"符号,为true时使用</param>
/// <returns></returns>
///
public string SHA1File( string curFileName, bool flag)
{
return HashFile(curFileName, "sha1",flag);
}
/// <summary>
/// 散列文件
/// </summary>
/// <param name="curFileName">要被散列的文件(全路径)</param>
/// <param name="algName">所用的散列算法名字,例如MD5,SHA1</param>
/// <param name="flag">散列值是否使用"-"符号,为true时使用</param>
/// <returns></returns>
private string HashFile( string curFileName, string algName, bool flag)
{
if (!System.IO.File.Exists(curFileName))
return string.Empty;
System.IO.FileStream fs = new System.IO.FileStream(curFileName, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
byte[] hashBytes = HashData(fs, algName);
fs.Close();
return ByteArrayToHexString(hashBytes,flag);
}
/// <summary>
/// 具体的散列实现
/// </summary>
/// <param name="stream">当前文件的流式</param>
/// <param name="algName">哈希算法名</param>
/// <returns></returns>
private byte[] HashData(System.IO.Stream stream, string algName)
{
System.Security.Cryptography.HashAlgorithm algorithm;
if ( string.Compare(algName, "sha1", true) == 0)
{
algorithm = System.Security.Cryptography.SHA1.Create();
}
else
{
if ( string.Compare(algName, "md5", true) != 0)
{
throw new Exception( "algName只能是sha1或md5");
}
algorithm = System.Security.Cryptography.MD5.Create();
}
return algorithm.ComputeHash(stream);
}
/// <summary>
/// 调整文件散列值的返回格式
/// </summary>
/// <param name="buf">文件散列值的二进制格式</param>
/// <param name="flag">散列值是否使用"-"符号,为true时使用</param>
/// <returns></returns>
private string ByteArrayToHexString( byte[] buf, bool flag)
{
if (flag)
{
return BitConverter.ToString(buf);
}
else
{
return BitConverter.ToString(buf).Replace( "-", "");
}
}
}
}