CryptographyUtils.cs 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  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) {
  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) {
  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)
  52. => ComputeHash(Encoding.UTF8.GetBytes(input), method);
  53. #endregion
  54. #region DES
  55. private static readonly byte[] desInitialVector = Encoding.UTF8.GetBytes("95168702");
  56. /// <summary>
  57. /// 未指定密钥时使用的默认 DES 密钥。必须为 8 字节。
  58. /// </summary>
  59. public static string defaultDesKey = "@;$ Abv2";
  60. /// <summary>
  61. /// 使用 DES 对称加密算法加密字符串。
  62. /// </summary>
  63. public static string DesEncrypt(string sourceString, string? key = null) {
  64. key = key is null ? defaultDesKey : key!.GetStableHashCode().ToString().EnsureLength('X', 8)[..8];
  65. byte[] btKey = Encoding.UTF8.GetBytes(key);
  66. var des = new DESCryptoServiceProvider();
  67. using var ms = new MemoryStream();
  68. using var cs = new CryptoStream(ms, des.CreateEncryptor(btKey, desInitialVector), CryptoStreamMode.Write);
  69. byte[] inData = Encoding.UTF8.GetBytes(sourceString);
  70. cs.Write(inData, 0, inData.Length);
  71. cs.FlushFinalBlock();
  72. return Convert.ToBase64String(ms.ToArray());
  73. }
  74. /// <summary>
  75. /// 使用 DES 对称加密算法解密字符串。
  76. /// </summary>
  77. public static string DesDecrypt(string encryptedString, string? key = null) {
  78. key = key is null ? defaultDesKey : key!.GetStableHashCode().ToString().EnsureLength('X', 8)[..8];
  79. byte[] btKey = Encoding.UTF8.GetBytes(key);
  80. var des = new DESCryptoServiceProvider();
  81. using var ms = new MemoryStream();
  82. using var cs = new CryptoStream(ms, des.CreateDecryptor(btKey, desInitialVector), CryptoStreamMode.Write);
  83. byte[] inData = Convert.FromBase64String(encryptedString);
  84. cs.Write(inData, 0, inData.Length);
  85. cs.FlushFinalBlock();
  86. return Encoding.UTF8.GetString(ms.ToArray());
  87. }
  88. #endregion
  89. #region ECDSA
  90. /// <summary>
  91. /// 未指定公钥时使用的默认 ECDSA P-256 公钥。
  92. /// </summary>
  93. public static string defaultEcdsaPublicKey = "RUNTMSAAAAC4QTUNAewh23Q4Q6koHkyIrDIIZUSbua23sf2DiZmIRwSzadISDRyTVTbuWniH3KR7rKj8XBsabms1be6i3c+S";
  94. /// <summary>
  95. /// 进行 ECDSA P-256 非对称加密签名验证。
  96. /// 如果验证失败则抛出 <see cref="CryptographicException"/>。
  97. /// </summary>
  98. public static void EcdsaVerify(string sourceString, string sign, string? publicKey = null) {
  99. using var sha256 = GetHashAlgorithm(HashMethod.Sha256);
  100. byte[] hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(sourceString));
  101. IntPtr algorithmHandle = IntPtr.Zero;
  102. IntPtr keyHandle = IntPtr.Zero;
  103. // 直接调用 DLL,以避免 .NET API 依赖的系统服务出现问题时导致验证失败
  104. try {
  105. int status = BCryptOpenAlgorithmProvider(out algorithmHandle, "ECDSA_P256", null, 0);
  106. if (status < 0) throw new CryptographicException($"{nameof(BCryptOpenAlgorithmProvider)} 失败,错误码 {status}");
  107. status = BCryptImportKeyPair(algorithmHandle, IntPtr.Zero, "ECCPUBLICBLOB", out keyHandle, Convert.FromBase64String(publicKey ?? defaultEcdsaPublicKey), 72, 0);
  108. if (status < 0) throw new CryptographicException($"{nameof(BCryptImportKeyPair)} 失败,错误码 {status}");
  109. status = BCryptVerifySignature(keyHandle, IntPtr.Zero, hash, hash.Length, Convert.FromBase64String(sign), 64, 0);
  110. if (status == unchecked((int) 0xC000A000)) throw new SecurityException("签名验证失败");
  111. if (status < 0) throw new CryptographicException($"{nameof(BCryptVerifySignature)} 失败,错误码 {status}");
  112. } finally {
  113. if (keyHandle != IntPtr.Zero) BCryptDestroyKey(keyHandle);
  114. if (algorithmHandle != IntPtr.Zero) BCryptCloseAlgorithmProvider(algorithmHandle, 0);
  115. }
  116. }
  117. [DllImport("bcrypt.dll", CharSet = CharSet.Unicode)] private static extern int BCryptOpenAlgorithmProvider(out IntPtr algorithmHandle, string algorithmId, string? implementation, int flags);
  118. [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);
  119. [DllImport("bcrypt.dll")] private static extern int BCryptVerifySignature(IntPtr keyHandle, IntPtr paddingInfo, byte[] hash, int hashSize, byte[] signature, int signatureSize, int flags);
  120. [DllImport("bcrypt.dll")] private static extern int BCryptDestroyKey(IntPtr keyHandle);
  121. [DllImport("bcrypt.dll")] private static extern int BCryptCloseAlgorithmProvider(IntPtr algorithmHandle, int flags);
  122. #endregion
  123. }