C# 擷取檔案MD5、SHA1

來源:互聯網
上載者:User
        /// <summary>
/// 計算檔案的 MD5 值
/// </summary>
/// <param name="fileName">要計算 MD5 值的檔案名稱和路徑</param>
/// <returns>MD5 值16進位字串</returns>
public string MD5File(string fileName)
{
return HashFile(fileName, "md5");
}

/// <summary>
/// 計算檔案的 sha1 值
/// </summary>
/// <param name="fileName">要計算 sha1 值的檔案名稱和路徑</param>
/// <returns>sha1 值16進位字串</returns>
public string SHA1File(string fileName)
{
return HashFile(fileName, "sha1");
}

/// <summary>
/// 計算檔案的雜湊值
/// </summary>
/// <param name="fileName">要計算雜湊值的檔案名稱和路徑</param>
/// <param name="algName">演算法:sha1,md5</param>
/// <returns>雜湊值16進位字串</returns>
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);
}

/// <summary>
/// 計算雜湊值
/// </summary>
/// <param name="stream">要計算雜湊值的 Stream</param>
/// <param name="algName">演算法:sha1,md5</param>
/// <returns>雜湊值位元組數組</returns>
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);
}

/// <summary>
/// 位元組數群組轉換為16進位表示的字串
/// </summary>
private string ByteArrayToHexString(byte[] buf)
{
return BitConverter.ToString(buf).Replace("-","");
}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.