CryptographyUtils.cs 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using System.Security;
  2. using System.Security.Cryptography;
  3. namespace MeloongCore;
  4. public static class CryptographyUtils {
  5. #region Hash
  6. public enum HashMethod { Md5, Sha1, Sha256, Sha512 }
  7. private static HashAlgorithm GetHashAlgorithm(HashMethod method) => method switch {
  8. HashMethod.Md5 => MD5.Create(),
  9. HashMethod.Sha1 => SHA1.Create(),
  10. HashMethod.Sha256 => SHA256.Create(),
  11. HashMethod.Sha512 => SHA512.Create(),
  12. _ => throw new ArgumentOutOfRangeException(nameof(method))
  13. };
  14. /// <summary>
  15. /// 计算文件的 Hash。返回十六进制小写字符串。
  16. /// </summary>
  17. public static string ComputeFileHash(string filePath, HashMethod method) {
  18. using HashAlgorithm hashImpl = GetHashAlgorithm(method);
  19. Logger.Trace($"计算文件 {method}:{filePath}");
  20. using var file = FileUtils.ReadAsStream(filePath);
  21. return BitConverter.ToString(hashImpl.ComputeHash(file)).Replace("-", "").ToLower();
  22. }
  23. /// <summary>
  24. /// 计算字节数组的 Hash。返回十六进制小写字符串。
  25. /// </summary>
  26. public static string ComputeBytesHash(byte[] input, HashMethod method) {
  27. using HashAlgorithm hashImpl = GetHashAlgorithm(method);
  28. return BitConverter.ToString(hashImpl.ComputeHash(input)).Replace("-", "").ToLower();
  29. }
  30. /// <summary>
  31. /// 计算字符串的 Hash。返回十六进制小写字符串。
  32. /// 使用 UTF-8 将字符串转换为字节数组。
  33. /// </summary>
  34. public static string ComputeStringHash(string input, HashMethod method)
  35. => ComputeBytesHash(Encoding.UTF8.GetBytes(input), method);
  36. #endregion
  37. #region ECDSA
  38. /// <summary>
  39. /// 进行 ECDSA P-256 签名验证。如果失败则抛出异常。
  40. /// </summary>
  41. public static void EcdsaVerify(string sourceString, string sign,
  42. string publicKeyBase64 = "RUNTMSAAAAC4QTUNAewh23Q4Q6koHkyIrDIIZUSbua23sf2DiZmIRwSzadISDRyTVTbuWniH3KR7rKj8XBsabms1be6i3c+S") {
  43. // 使用 Windows CNG API 直接处理原始公钥和签名数据,以避免 .NET API 的兼容性问题
  44. using var sha256 = GetHashAlgorithm(HashMethod.Sha256);
  45. byte[] hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(sourceString));
  46. IntPtr algorithmHandle = IntPtr.Zero;
  47. IntPtr keyHandle = IntPtr.Zero;
  48. try {
  49. int status = BCryptOpenAlgorithmProvider(out algorithmHandle, "ECDSA_P256", null, 0);
  50. if (status < 0) throw new CryptographicException($"{nameof(BCryptOpenAlgorithmProvider)} 失败,错误码 {status}");
  51. status = BCryptImportKeyPair(algorithmHandle, IntPtr.Zero, "ECCPUBLICBLOB", out keyHandle, Convert.FromBase64String(publicKeyBase64), 72, 0);
  52. if (status < 0) throw new CryptographicException($"{nameof(BCryptImportKeyPair)} 失败,错误码 {status}");
  53. status = BCryptVerifySignature(keyHandle, IntPtr.Zero, hash, hash.Length, Convert.FromBase64String(sign), 64, 0);
  54. if (status == unchecked((int) 0xC000A000)) throw new SecurityException("签名验证失败");
  55. if (status < 0) throw new CryptographicException($"{nameof(BCryptVerifySignature)} 失败,错误码 {status}");
  56. } finally {
  57. if (keyHandle != IntPtr.Zero) BCryptDestroyKey(keyHandle);
  58. if (algorithmHandle != IntPtr.Zero) BCryptCloseAlgorithmProvider(algorithmHandle, 0);
  59. }
  60. }
  61. [DllImport("bcrypt.dll", CharSet = CharSet.Unicode)] private static extern int BCryptOpenAlgorithmProvider(out IntPtr algorithmHandle, string algorithmId, string? implementation, int flags);
  62. [DllImport("bcrypt.dll", CharSet = CharSet.Unicode)] private static extern int BCryptImportKeyPair(IntPtr algorithmHandle, IntPtr importKey, string blobType, out IntPtr keyHandle, byte[] input, int inputSize, int flags);
  63. [DllImport("bcrypt.dll")] private static extern int BCryptVerifySignature(IntPtr keyHandle, IntPtr paddingInfo, byte[] hash, int hashSize, byte[] signature, int signatureSize, int flags);
  64. [DllImport("bcrypt.dll")] private static extern int BCryptDestroyKey(IntPtr keyHandle);
  65. [DllImport("bcrypt.dll")] private static extern int BCryptCloseAlgorithmProvider(IntPtr algorithmHandle, int flags);
  66. #endregion
  67. }