CryptographyUtils.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  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 AES 对称加解密
  55. private const byte AesDataVersion = 1;
  56. /// <summary>
  57. /// 使用 AES-256-CBC 对称加密字符串。
  58. /// </summary>
  59. /// <returns>加密后的 Base64 字符串。若输入为空字符串或 null,则原样返回空字符串或 null。</returns>
  60. public static string? AesEncrypt(string? sourceString, string key = "EncryptKey") {
  61. if (string.IsNullOrEmpty(sourceString)) return sourceString; // 原样返回空字符串或 null
  62. byte[] iv = new byte[AesIvSize];
  63. using var rng = RandomNumberGenerator.Create();
  64. rng.GetBytes(iv);
  65. byte[] cipherBytes;
  66. using var sha256 = SHA256.Create();
  67. byte[] aesKey = sha256.ComputeHash(Encoding.UTF8.GetBytes(key));
  68. byte[] hmacKey = sha256.ComputeHash(Encoding.UTF8.GetBytes("AES-HMAC|" + key));
  69. using Aes aes = Aes.Create();
  70. aes.Mode = CipherMode.CBC;
  71. aes.Padding = PaddingMode.PKCS7;
  72. using ICryptoTransform encryptor = aes.CreateEncryptor(aesKey, iv);
  73. byte[] sourceBytes = Encoding.UTF8.GetBytes(sourceString);
  74. cipherBytes = encryptor.TransformFinalBlock(sourceBytes, 0, sourceBytes.Length);
  75. // 格式:版本 [1 字节] | IV [16 字节] | 密文 [N 字节] | 校验 [4 字节]
  76. byte[] encryptedBytes = new byte[1 + iv.Length + cipherBytes.Length + AesCheckSize];
  77. encryptedBytes[0] = AesDataVersion;
  78. Array.Copy(iv, 0, encryptedBytes, 1, iv.Length);
  79. Array.Copy(cipherBytes, 0, encryptedBytes, 1 + iv.Length, cipherBytes.Length);
  80. using var hmac = new HMACSHA256(hmacKey);
  81. byte[] checkBytes = hmac.ComputeHash(encryptedBytes, 0, 1 + iv.Length + cipherBytes.Length);
  82. Array.Copy(checkBytes, 0, encryptedBytes, 1 + iv.Length + cipherBytes.Length, AesCheckSize);
  83. return Convert.ToBase64String(encryptedBytes);
  84. }
  85. /// <summary>
  86. /// 使用 AES-256-CBC 对称解密字符串。
  87. /// 如果输入数据有误,则确保会抛出 <see cref="CryptographicException"/>。
  88. /// </summary>
  89. /// <returns>解密后的字符串。若输入为空字符串或 null,则原样返回空字符串或 null。</returns>
  90. public static string? AesDecrypt(string? encryptedString, string key = "EncryptKey") {
  91. if (string.IsNullOrEmpty(encryptedString)) return encryptedString; // 原样返回空字符串或 null
  92. byte[] encryptedBytes;
  93. try {
  94. encryptedBytes = Convert.FromBase64String(encryptedString);
  95. } catch (FormatException ex) {
  96. throw new CryptographicException($"数据不是一个有效的 Base64 字符串({encryptedString})", ex);
  97. }
  98. if (encryptedBytes.Length == 0) throw new CryptographicException($"对称加密数据长度有误({encryptedString})");
  99. int cipherSize = encryptedBytes.Length - 1 - AesIvSize - AesCheckSize;
  100. if (encryptedBytes[0] != AesDataVersion || cipherSize < 16 || cipherSize % 16 != 0)
  101. throw new CryptographicException($"对称加密数据长度有误({encryptedString})");
  102. using var sha256 = SHA256.Create();
  103. byte[] hmacKey = sha256.ComputeHash(Encoding.UTF8.GetBytes("AES-HMAC|" + key));
  104. using var hmac = new HMACSHA256(hmacKey);
  105. byte[] checkBytes = hmac.ComputeHash(encryptedBytes, 0, 1 + AesIvSize + cipherSize);
  106. int checkOffset = 1 + AesIvSize + cipherSize;
  107. int checkDiff = 0;
  108. for (int i = 0; i < AesCheckSize; i++)
  109. checkDiff |= encryptedBytes[checkOffset + i] ^ checkBytes[i];
  110. if (checkDiff != 0) throw new CryptographicException($"对称加密数据校验失败({encryptedString})");
  111. byte[] aesKey = sha256.ComputeHash(Encoding.UTF8.GetBytes(key));
  112. byte[] iv = new byte[AesIvSize];
  113. Array.Copy(encryptedBytes, 1, iv, 0, iv.Length);
  114. using Aes aes = Aes.Create();
  115. aes.Mode = CipherMode.CBC;
  116. aes.Padding = PaddingMode.PKCS7;
  117. using ICryptoTransform decryptor = aes.CreateDecryptor(aesKey, iv);
  118. byte[] output = decryptor.TransformFinalBlock(encryptedBytes, 1 + iv.Length, cipherSize);
  119. return Encoding.UTF8.GetString(output);
  120. }
  121. private const int AesIvSize = 16;
  122. private const int AesCheckSize = 4;
  123. #endregion
  124. #region ECDSA 非对称加密签名
  125. /// <summary>
  126. /// 使用 ECDSA 算法,验证一个字符串的签名是否使用私钥生成。
  127. /// 如果验证失败则抛出 <see cref="CryptographicException"/>。
  128. /// </summary>
  129. public static void EcdsaVerify(string sourceString, string sign, string publicKey) {
  130. using var sha256 = GetHashAlgorithm(HashMethod.Sha256);
  131. byte[] hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(sourceString));
  132. IntPtr algorithmHandle = IntPtr.Zero;
  133. IntPtr keyHandle = IntPtr.Zero;
  134. // 直接调用 DLL,以避免 .NET API 依赖的系统服务存在问题
  135. try {
  136. int status = BCryptOpenAlgorithmProvider(out algorithmHandle, "ECDSA_P256", null, 0);
  137. if (status < 0) throw new CryptographicException($"{nameof(BCryptOpenAlgorithmProvider)} 失败,错误码 {status}");
  138. status = BCryptImportKeyPair(algorithmHandle, IntPtr.Zero, "ECCPUBLICBLOB", out keyHandle, Convert.FromBase64String(publicKey), 72, 0);
  139. if (status < 0) throw new CryptographicException($"{nameof(BCryptImportKeyPair)} 失败,错误码 {status}");
  140. status = BCryptVerifySignature(keyHandle, IntPtr.Zero, hash, hash.Length, Convert.FromBase64String(sign), 64, 0);
  141. if (status == unchecked((int) 0xC000A000)) throw new SecurityException("签名验证失败");
  142. if (status < 0) throw new CryptographicException($"{nameof(BCryptVerifySignature)} 失败,错误码 {status}");
  143. } finally {
  144. if (keyHandle != IntPtr.Zero) BCryptDestroyKey(keyHandle);
  145. if (algorithmHandle != IntPtr.Zero) BCryptCloseAlgorithmProvider(algorithmHandle, 0);
  146. }
  147. }
  148. /// <summary>
  149. /// 使用 ECDSA 算法,为一个双方均知晓的字符串生成签名。
  150. /// </summary>
  151. public static string EcdsaSign(string sourceString, string privateKey) {
  152. using var sha256 = GetHashAlgorithm(HashMethod.Sha256);
  153. byte[] hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(sourceString));
  154. byte[] privateKeyBytes = Convert.FromBase64String(privateKey);
  155. IntPtr algorithmHandle = IntPtr.Zero;
  156. IntPtr keyHandle = IntPtr.Zero;
  157. // 直接调用 DLL,避免 .NET API 依赖的系统服务存在问题
  158. try {
  159. int status = BCryptOpenAlgorithmProvider(out algorithmHandle, "ECDSA_P256", null, 0);
  160. if (status < 0) throw new CryptographicException($"{nameof(BCryptOpenAlgorithmProvider)} 失败,错误码 {status}");
  161. status = BCryptImportKeyPair(algorithmHandle, IntPtr.Zero, "ECCPRIVATEBLOB", out keyHandle, privateKeyBytes, privateKeyBytes.Length, 0);
  162. if (status < 0) throw new CryptographicException($"{nameof(BCryptImportKeyPair)} 失败,错误码 {status}");
  163. status = BCryptSignHash(keyHandle, IntPtr.Zero, hash, hash.Length, null, 0, out int signSize, 0);
  164. if (status < 0) throw new CryptographicException($"{nameof(BCryptSignHash)} 失败,错误码 {status}");
  165. byte[] sign = new byte[signSize];
  166. status = BCryptSignHash(keyHandle, IntPtr.Zero, hash, hash.Length, sign, sign.Length, out int actualSignSize, 0);
  167. if (status < 0) throw new CryptographicException($"{nameof(BCryptSignHash)} 失败,错误码 {status}");
  168. if (actualSignSize != sign.Length) Array.Resize(ref sign, actualSignSize);
  169. return Convert.ToBase64String(sign);
  170. } finally {
  171. if (keyHandle != IntPtr.Zero) BCryptDestroyKey(keyHandle);
  172. if (algorithmHandle != IntPtr.Zero) BCryptCloseAlgorithmProvider(algorithmHandle, 0);
  173. }
  174. }
  175. [DllImport("bcrypt.dll", CharSet = CharSet.Unicode)] private static extern int BCryptOpenAlgorithmProvider(out IntPtr algorithmHandle, string algorithmId, string? implementation, int flags);
  176. [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);
  177. [DllImport("bcrypt.dll")] private static extern int BCryptVerifySignature(IntPtr keyHandle, IntPtr paddingInfo, byte[] hash, int hashSize, byte[] signature, int signatureSize, int flags);
  178. [DllImport("bcrypt.dll")] private static extern int BCryptDestroyKey(IntPtr keyHandle);
  179. [DllImport("bcrypt.dll")] private static extern int BCryptCloseAlgorithmProvider(IntPtr algorithmHandle, int flags);
  180. [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);
  181. #endregion
  182. }