在代码过程中,把开发过程中比较常用的代码段做个珍藏,如下的代码是关于C# 输出MD5和SHA1编码的代码,应该能对大家有所用途。
using System;
namespace myMethod
{
class computeMD5andSHA1
{
public string MD5File(string fileName)
{
return HashFile(fileName , "md5");
}
public string SHA1File(string fileName)
{
return HashFile(fileName , "sha1");
}
private string HashFile(string fileName , string algName)
{
if ( !System.IO.File.Exists(fileName) )
return string.Empty;
System.IO.FileStream fs = new System.IO.FileStream(fileName , System.IO.FileMode.Open , System.IO.FileAccess.Read);
byte[] hashBytes = HashData(fs , algName);
fs.Close();
return ByteArrayToHexString(hashBytes);
}
private byte[] HashData(System.IO.Stream stream , string algName)
{
System.Security.Cryptography.HashAlgorithm algorithm;
if ( algName == null )
{
throw new ArgumentNullException("algName 不能为 null");
}
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);
}
private string ByteArrayToHexString(byte[] buf)
{
return BitConverter.ToString(buf).Replace("-" , "");
}
}
}