CryptographyUtils.cs 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. using System.Security;
  2. using System.Security.Cryptography;
  3. namespace MeloongCore;
  4. public static class CryptographyUtils {
  5. #region Hash
  6. public enum HashMethod {
  7. /// <summary>
  8. /// 使用 <see cref="MD5"/> 算法。在 16 进制下哈希为 32 长度字符串。
  9. /// </summary>
  10. Md5,
  11. /// <summary>
  12. /// 使用 <see cref="SHA1"/> 算法。在 16 进制下哈希为 40 长度字符串。
  13. /// </summary>
  14. Sha1,
  15. /// <summary>
  16. /// 使用 <see cref="SHA256"/> 算法。在 16 进制下哈希为 64 长度字符串。
  17. /// </summary>
  18. Sha256,
  19. /// <summary>
  20. /// 使用 <see cref="SHA512"/> 算法。在 16 进制下哈希为 128 长度字符串。
  21. /// </summary>
  22. Sha512
  23. }
  24. private static HashAlgorithm GetHashAlgorithm(HashMethod method) => method switch {
  25. HashMethod.Md5 => MD5.Create(),
  26. HashMethod.Sha1 => SHA1.Create(),
  27. HashMethod.Sha256 => SHA256.Create(),
  28. HashMethod.Sha512 => SHA512.Create(),
  29. _ => throw new ArgumentOutOfRangeException(nameof(method))
  30. };
  31. /// <summary>
  32. /// 计算文件的 Hash。返回 16 进制小写字符串。
  33. /// </summary>
  34. public static string ComputeFileHash(string filePath, HashMethod method = HashMethod.Md5) {
  35. using HashAlgorithm hashImpl = GetHashAlgorithm(method);
  36. Logger.Trace($"计算文件 {method}:{filePath}");
  37. using var file = FileUtils.ReadAsStream(filePath);
  38. return BitConverter.ToString(hashImpl.ComputeHash(file)).Replace("-", "").Lower();
  39. }
  40. /// <summary>
  41. /// 计算字节数组的 Hash。返回 16 进制小写字符串。
  42. /// </summary>
  43. public static string ComputeHash(byte[] input, HashMethod method = HashMethod.Md5) {
  44. using HashAlgorithm hashImpl = GetHashAlgorithm(method);
  45. return BitConverter.ToString(hashImpl.ComputeHash(input)).Replace("-", "").Lower();
  46. }
  47. /// <summary>
  48. /// 计算字符串的 Hash。返回 16 进制小写字符串。
  49. /// <para/> 使用 UTF-8 将字符串转换为字节数组。
  50. /// </summary>
  51. public static string ComputeHash(string input, HashMethod method = HashMethod.Md5)
  52. => ComputeHash(Encoding.UTF8.GetBytes(input), method);
  53. #endregion
  54. #region ECDSA
  55. /// <summary>
  56. /// 未指定公钥时的默认 ECDSA P-256 公钥。
  57. /// </summary>
  58. public static string DefaultEcdsaPublicKey = "RUNTMSAAAAC4QTUNAewh23Q4Q6koHkyIrDIIZUSbua23sf2DiZmIRwSzadISDRyTVTbuWniH3KR7rKj8XBsabms1be6i3c+S";
  59. /// <summary>
  60. /// 进行 ECDSA P-256 非对称加密签名验证。
  61. /// 如果验证失败则抛出 <see cref="CryptographicException"/>。
  62. /// </summary>
  63. public static void EcdsaVerify(string sourceString, string sign, string? publicKey = null) {
  64. using var sha256 = GetHashAlgorithm(HashMethod.Sha256);
  65. byte[] hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(sourceString));
  66. IntPtr algorithmHandle = IntPtr.Zero;
  67. IntPtr keyHandle = IntPtr.Zero;
  68. // 直接调用 DLL,以避免 .NET API 依赖的系统服务出现问题时导致验证失败
  69. try {
  70. int status = BCryptOpenAlgorithmProvider(out algorithmHandle, "ECDSA_P256", null, 0);
  71. if (status < 0) throw new CryptographicException($"{nameof(BCryptOpenAlgorithmProvider)} 失败,错误码 {status}");
  72. status = BCryptImportKeyPair(algorithmHandle, IntPtr.Zero, "ECCPUBLICBLOB", out keyHandle, Convert.FromBase64String(publicKey ?? DefaultEcdsaPublicKey), 72, 0);
  73. if (status < 0) throw new CryptographicException($"{nameof(BCryptImportKeyPair)} 失败,错误码 {status}");
  74. status = BCryptVerifySignature(keyHandle, IntPtr.Zero, hash, hash.Length, Convert.FromBase64String(sign), 64, 0);
  75. if (status == unchecked((int) 0xC000A000)) throw new SecurityException("签名验证失败");
  76. if (status < 0) throw new CryptographicException($"{nameof(BCryptVerifySignature)} 失败,错误码 {status}");
  77. } finally {
  78. if (keyHandle != IntPtr.Zero) BCryptDestroyKey(keyHandle);
  79. if (algorithmHandle != IntPtr.Zero) BCryptCloseAlgorithmProvider(algorithmHandle, 0);
  80. }
  81. }
  82. [DllImport("bcrypt.dll", CharSet = CharSet.Unicode)] private static extern int BCryptOpenAlgorithmProvider(out IntPtr algorithmHandle, string algorithmId, string? implementation, int flags);
  83. [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);
  84. [DllImport("bcrypt.dll")] private static extern int BCryptVerifySignature(IntPtr keyHandle, IntPtr paddingInfo, byte[] hash, int hashSize, byte[] signature, int signatureSize, int flags);
  85. [DllImport("bcrypt.dll")] private static extern int BCryptDestroyKey(IntPtr keyHandle);
  86. [DllImport("bcrypt.dll")] private static extern int BCryptCloseAlgorithmProvider(IntPtr algorithmHandle, int flags);
  87. #endregion
  88. }