[ECDSA使用Java的公共密钥和签名验证C#中的签名

问题描述 投票:1回答:1

我有一个用Java生成的公钥和签名,我想使用ECDsaCng在C#中进行验证。公开密钥为MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAExeg15CVOUcspdO0Pm27hPVx50thn0CGk3/3NLl08qcK+0U7cesOUUwxQetMgtUHrh0lNao5XRAAurhcBtZpo6w==

通过将最后64个字节并在其前面加上0x45、0x43、0x53、0x31等,将其转换为C#ECDsaCng可以使用的键。

签名是使用SHA256在Java中生成的。有趣的是,如果我使用此处的工具https://kjur.github.io/jsrsasign/sample/sample-ecdsa.html测试签名,则表示它是有效的签名。

我一直在网上搜寻,但仍然没有喜悦。

代码如下

static void VerifySignature()
{
  var publicKey = "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAExeg15CVOUcspdO0Pm27hPVx50thn0CGk3/3NLl08qcK+0U7cesOUUwxQetMgtUHrh0lNao5XRAAurhcBtZpo6w==";
  byte[] publicKeyBytes = Convert.FromBase64String(publicKey);

  var keyType = new byte[] { 0x45, 0x43, 0x53, 0x31 };
  var keyLength = new byte[] { 0x20, 0x00, 0x00, 0x00 };
  var key = keyType.Concat(keyLength).Concat(publicKeyBytes.TakeLast(64)).ToArray(); // 4543533120000000c5e835e4254e51cb2974ed0f9b6ee13d5c79d2d867d021a4dffdcd2e5d3ca9c2bed14edc7ac394530c507ad320b541eb87494d6a8e5744002eae1701b59a68eb

  // For testing in online tool
  Debug.WriteLine(ByteArrayToString(publicKeyBytes.TakeLast(65).ToArray())); //04c5e835e4254e51cb2974ed0f9b6ee13d5c79d2d867d021a4dffdcd2e5d3ca9c2bed14edc7ac394530c507ad320b541eb87494d6a8e5744002eae1701b59a68eb


  var signature = "MEQCIFNEZQRzIrvr6dtJ4j4HP8nXHSts3w3qsRt8cFXBaOGAAiAJO/EjzCZlNLQSvKBinVHfSvTEmor0dc3YX7FPMnnYCg==";
            var signatureBytes = Convert.FromBase64String(signature); // 30440220534465047322bbebe9db49e23e073fc9d71d2b6cdf0deab11b7c7055c168e1800220093bf123cc266534b412bca0629d51df4af4c49a8af475cdd85fb14f3279d80a

  var data = Encoding.UTF8.GetBytes("ABCDEFGH");

  CngKey cngKey = CngKey.Import(key, CngKeyBlobFormat.EccPublicBlob);
  ECDsaCng eCDsaCng = new ECDsaCng(cngKey);

  bool result = eCDsaCng.VerifyData(data, signatureBytes); // result is false

  string ByteArrayToString(byte[] ba)
  {
    StringBuilder hex = new StringBuilder(ba.Length * 2);
    foreach (byte b in ba)
      hex.AppendFormat("{0:x2}", b);

    return hex.ToString();
  }
}


c# signature verify ecdsa
1个回答
2
投票
原因是不同的格式。 Microsoft希望格式为r|s,而您的签名是以ASN.1格式指定的(在ECDSA here的上下文中对此进行了说明):
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.