HashUtils.cs 875 B

1234567891011121314151617181920212223
  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. Logger.Trace($"计算文件 {method}:{filePath}");
  18. return BitConverter.ToString(hashImpl.ComputeHash(file)).Replace("-", "").ToLower();
  19. }
  20. }