CryptographyUtils.cs 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  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. /// 如果验证失败则抛出 <see cref="CryptographicException"/>。
  58. /// </summary>
  59. public static void EcdsaVerify(string sourceString, string sign, string publicKey) {
  60. using var sha256 = GetHashAlgorithm(HashMethod.Sha256);
  61. byte[] hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(sourceString));
  62. IntPtr algorithmHandle = IntPtr.Zero;
  63. IntPtr keyHandle = IntPtr.Zero;
  64. // 直接调用 DLL,以避免 .NET API 依赖的系统服务存在问题
  65. try {
  66. int status = BCryptOpenAlgorithmProvider(out algorithmHandle, "ECDSA_P256", null, 0);
  67. if (status < 0) throw new CryptographicException($"{nameof(BCryptOpenAlgorithmProvider)} 失败,错误码 {status}");
  68. status = BCryptImportKeyPair(algorithmHandle, IntPtr.Zero, "ECCPUBLICBLOB", out keyHandle, Convert.FromBase64String(publicKey), 72, 0);
  69. if (status < 0) throw new CryptographicException($"{nameof(BCryptImportKeyPair)} 失败,错误码 {status}");
  70. status = BCryptVerifySignature(keyHandle, IntPtr.Zero, hash, hash.Length, Convert.FromBase64String(sign), 64, 0);
  71. if (status == unchecked((int) 0xC000A000)) throw new SecurityException("签名验证失败");
  72. if (status < 0) throw new CryptographicException($"{nameof(BCryptVerifySignature)} 失败,错误码 {status}");
  73. } finally {
  74. if (keyHandle != IntPtr.Zero) BCryptDestroyKey(keyHandle);
  75. if (algorithmHandle != IntPtr.Zero) BCryptCloseAlgorithmProvider(algorithmHandle, 0);
  76. }
  77. }
  78. /// <summary>
  79. /// 使用 ECDSA 算法,为一个双方均知晓的字符串生成签名。
  80. /// </summary>
  81. public static string EcdsaSign(string sourceString, string privateKey) {
  82. using var sha256 = GetHashAlgorithm(HashMethod.Sha256);
  83. byte[] hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(sourceString));
  84. byte[] privateKeyBytes = Convert.FromBase64String(privateKey);
  85. IntPtr algorithmHandle = IntPtr.Zero;
  86. IntPtr keyHandle = IntPtr.Zero;
  87. // 直接调用 DLL,避免 .NET API 依赖的系统服务存在问题
  88. try {
  89. int status = BCryptOpenAlgorithmProvider(out algorithmHandle, "ECDSA_P256", null, 0);
  90. if (status < 0) throw new CryptographicException($"{nameof(BCryptOpenAlgorithmProvider)} 失败,错误码 {status}");
  91. status = BCryptImportKeyPair(algorithmHandle, IntPtr.Zero, "ECCPRIVATEBLOB", out keyHandle, privateKeyBytes, privateKeyBytes.Length, 0);
  92. if (status < 0) throw new CryptographicException($"{nameof(BCryptImportKeyPair)} 失败,错误码 {status}");
  93. status = BCryptSignHash(keyHandle, IntPtr.Zero, hash, hash.Length, null, 0, out int signSize, 0);
  94. if (status < 0) throw new CryptographicException($"{nameof(BCryptSignHash)} 失败,错误码 {status}");
  95. byte[] sign = new byte[signSize];
  96. status = BCryptSignHash(keyHandle, IntPtr.Zero, hash, hash.Length, sign, sign.Length, out int actualSignSize, 0);
  97. if (status < 0) throw new CryptographicException($"{nameof(BCryptSignHash)} 失败,错误码 {status}");
  98. if (actualSignSize != sign.Length) Array.Resize(ref sign, actualSignSize);
  99. return Convert.ToBase64String(sign);
  100. } finally {
  101. if (keyHandle != IntPtr.Zero) BCryptDestroyKey(keyHandle);
  102. if (algorithmHandle != IntPtr.Zero) BCryptCloseAlgorithmProvider(algorithmHandle, 0);
  103. }
  104. }
  105. [DllImport("bcrypt.dll", CharSet = CharSet.Unicode)] private static extern int BCryptOpenAlgorithmProvider(out IntPtr algorithmHandle, string algorithmId, string? implementation, int flags);
  106. [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);
  107. [DllImport("bcrypt.dll")] private static extern int BCryptVerifySignature(IntPtr keyHandle, IntPtr paddingInfo, byte[] hash, int hashSize, byte[] signature, int signatureSize, int flags);
  108. [DllImport("bcrypt.dll")] private static extern int BCryptDestroyKey(IntPtr keyHandle);
  109. [DllImport("bcrypt.dll")] private static extern int BCryptCloseAlgorithmProvider(IntPtr algorithmHandle, int flags);
  110. [DllImport("bcrypt.dll")] private static extern int BCryptSignHash(IntPtr keyHandle, IntPtr paddingInfo, byte[] hash, int hashSize, byte[]? signature, int signatureSize, out int resultSize, int flags);
  111. #endregion
  112. }