HashUtils.cs 814 B

12345678910111213141516171819202122
  1. using System.Security.Cryptography;
  2. namespace MeloongCore;
  3. public static class HashUtils {
  4. public enum HashMethod { Md5, Sha1, Sha256, Sha512 }
  5. /// <summary>
  6. /// 计算文件的哈希值(十六进制小写)。
  7. /// </summary>
  8. public static string ComputeFromFile(string filePath, HashMethod method) {
  9. using var file = FileUtils.ReadAsStream(filePath);
  10. using HashAlgorithm hashImpl = method switch {
  11. HashMethod.Md5 => MD5.Create(),
  12. HashMethod.Sha1 => SHA1.Create(),
  13. HashMethod.Sha256 => SHA256.Create(),
  14. HashMethod.Sha512 => SHA512.Create(),
  15. _ => throw new ArgumentOutOfRangeException(nameof(method))
  16. };
  17. return BitConverter.ToString(hashImpl.ComputeHash(file)).Replace("-", "").ToLower();
  18. }
  19. }