Explorar o código

ECDSA 的完整实现

龙腾猫跃 hai 4 meses
pai
achega
fbc7565d7b
Modificáronse 1 ficheiros con 33 adicións e 8 borrados
  1. 33 8
      Shared/Utils/CryptographyUtils.cs

+ 33 - 8
Shared/Utils/CryptographyUtils.cs

@@ -60,25 +60,20 @@ public static class CryptographyUtils {
 
     #region ECDSA
 
-    /// <summary>
-    /// 未指定公钥时的默认 ECDSA P-256 公钥。
-    /// </summary>
-    public static string DefaultEcdsaPublicKey = "RUNTMSAAAAC4QTUNAewh23Q4Q6koHkyIrDIIZUSbua23sf2DiZmIRwSzadISDRyTVTbuWniH3KR7rKj8XBsabms1be6i3c+S";
-
     /// <summary>
     /// 进行 ECDSA P-256 非对称加密签名验证。
     /// 如果验证失败则抛出 <see cref="CryptographicException"/>。
     /// </summary>
-    public static void EcdsaVerify(string sourceString, string sign, string? publicKey = null) {
+    public static void EcdsaVerify(string sourceString, string sign, string publicKey) {
         using var sha256 = GetHashAlgorithm(HashMethod.Sha256);
         byte[] hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(sourceString));
         IntPtr algorithmHandle = IntPtr.Zero;
         IntPtr keyHandle = IntPtr.Zero;
-        // 直接调用 DLL,以避免 .NET API 依赖的系统服务出现问题时导致验证失败
+        // 直接调用 DLL,以避免 .NET API 依赖的系统服务存在问题
         try {
             int status = BCryptOpenAlgorithmProvider(out algorithmHandle, "ECDSA_P256", null, 0);
             if (status < 0) throw new CryptographicException($"{nameof(BCryptOpenAlgorithmProvider)} 失败,错误码 {status}");
-            status = BCryptImportKeyPair(algorithmHandle, IntPtr.Zero, "ECCPUBLICBLOB", out keyHandle, Convert.FromBase64String(publicKey ?? DefaultEcdsaPublicKey), 72, 0);
+            status = BCryptImportKeyPair(algorithmHandle, IntPtr.Zero, "ECCPUBLICBLOB", out keyHandle, Convert.FromBase64String(publicKey), 72, 0);
             if (status < 0) throw new CryptographicException($"{nameof(BCryptImportKeyPair)} 失败,错误码 {status}");
             status = BCryptVerifySignature(keyHandle, IntPtr.Zero, hash, hash.Length, Convert.FromBase64String(sign), 64, 0);
             if (status == unchecked((int) 0xC000A000)) throw new SecurityException("签名验证失败");
@@ -88,11 +83,41 @@ public static class CryptographyUtils {
             if (algorithmHandle != IntPtr.Zero) BCryptCloseAlgorithmProvider(algorithmHandle, 0);
         }
     }
+
+    /// <summary>
+    /// 使用 ECDSA 算法,为一个双方均知晓的字符串生成签名。
+    /// </summary>
+    public static string EcdsaSign(string sourceString, string privateKey) {
+        using var sha256 = GetHashAlgorithm(HashMethod.Sha256);
+        byte[] hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(sourceString));
+        byte[] privateKeyBytes = Convert.FromBase64String(privateKey);
+        IntPtr algorithmHandle = IntPtr.Zero;
+        IntPtr keyHandle = IntPtr.Zero;
+        // 直接调用 DLL,避免 .NET API 依赖的系统服务存在问题
+        try {
+            int status = BCryptOpenAlgorithmProvider(out algorithmHandle, "ECDSA_P256", null, 0);
+            if (status < 0) throw new CryptographicException($"{nameof(BCryptOpenAlgorithmProvider)} 失败,错误码 {status}");
+            status = BCryptImportKeyPair(algorithmHandle, IntPtr.Zero, "ECCPRIVATEBLOB", out keyHandle, privateKeyBytes, privateKeyBytes.Length, 0);
+            if (status < 0) throw new CryptographicException($"{nameof(BCryptImportKeyPair)} 失败,错误码 {status}");
+            status = BCryptSignHash(keyHandle, IntPtr.Zero, hash, hash.Length, null, 0, out int signSize, 0);
+            if (status < 0) throw new CryptographicException($"{nameof(BCryptSignHash)} 失败,错误码 {status}");
+            byte[] sign = new byte[signSize];
+            status = BCryptSignHash(keyHandle, IntPtr.Zero, hash, hash.Length, sign, sign.Length, out int actualSignSize, 0);
+            if (status < 0) throw new CryptographicException($"{nameof(BCryptSignHash)} 失败,错误码 {status}");
+            if (actualSignSize != sign.Length) Array.Resize(ref sign, actualSignSize);
+            return Convert.ToBase64String(sign);
+        } finally {
+            if (keyHandle != IntPtr.Zero) BCryptDestroyKey(keyHandle);
+            if (algorithmHandle != IntPtr.Zero) BCryptCloseAlgorithmProvider(algorithmHandle, 0);
+        }
+    }
+
     [DllImport("bcrypt.dll", CharSet = CharSet.Unicode)] private static extern int BCryptOpenAlgorithmProvider(out IntPtr algorithmHandle, string algorithmId, string? implementation, int flags);
     [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);
     [DllImport("bcrypt.dll")] private static extern int BCryptVerifySignature(IntPtr keyHandle, IntPtr paddingInfo, byte[] hash, int hashSize, byte[] signature, int signatureSize, int flags);
     [DllImport("bcrypt.dll")] private static extern int BCryptDestroyKey(IntPtr keyHandle);
     [DllImport("bcrypt.dll")] private static extern int BCryptCloseAlgorithmProvider(IntPtr algorithmHandle, int flags);
+    [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);
 
     #endregion