gpt4 book ai didi

c# - 在 C# 中使用 Bouncy CaSTLe 验证 ECDSA 签名

转载 作者:行者123 更新时间:2023-11-30 19:55:26 25 4
gpt4 key购买 nike

我尝试在 C# 的 Bouncy CaSTLe 中验证 ECDSA 签名时遇到问题。代码是从我手头的Java例子中借鉴过来的,所以我100%确定公钥和签名是正确的。但是 C# 实现总是返回签名无效。我检查了曲线参数,它们是正确的。我尝试使用 DER 和“原始”签名,但还是没有用。

谁能发现我做错了什么:

namespace TestECDSA
{
class Program
{
static void Main(string[] args)
{
byte[] b = new byte[] { 0x2B, 0xA1, 0x41, 0x00 };

string pubKey = "044F6D3F294DEA5737F0F46FFEE88A356EED95695DD7E0C27A591E6F6F65962BAF";
string signature = "AAD03D3D38CE53B673CF8F1C016C8D3B67EA98CBCF72627788368C7C54AA2FC4";

X9ECParameters curve = SecNamedCurves.GetByName("secp128r1");
ECDomainParameters curveSpec = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H, curve.GetSeed());

ECPublicKeyParameters key = new ECPublicKeyParameters("ECDSA", curve.Curve.DecodePoint(Hex.Decode(pubKey)), curveSpec);

ISigner signer = SignerUtilities.GetSigner("NONEwithECDSA");

signer.Init(false, key);

signer.BlockUpdate(b, 0, b.Length);

if (signer.VerifySignature(derEncodeSignature(Hex.Decode(signature))))
System.Console.WriteLine("Verified Signature");
else
System.Console.WriteLine("Not Verified Signature");
}

public static byte[] derEncodeSignature(byte[] signature)
{
byte[] encoded = new byte[6 + signature.Length];

byte[] r = RangeSubset(signature, 0, 16);
byte[] s = RangeSubset(signature, 16, 16);

encoded[0] = 0x30;
encoded[1] = 0x24;
encoded[2] = 0x02;
encoded[3] = 0x10;

encoded[4 + r.Length] = 0x02;
encoded[5 + r.Length] = 0x10;

Array.Copy(r, 0, encoded, 4, r.Length);
Array.Copy(s, 0, encoded, 6 + r.Length, r.Length);

return encoded;
}

public static T[] RangeSubset<T>(T[] array, int startIndex, int length)
{
T[] subset = new T[length];
Array.Copy(array, startIndex, subset, 0, length);
return subset;
}
}
}

最佳答案

您可以像这样使用 signer.GenerateSignature() 而不是自己对签名进行 DER 编码:

        var signerAlgorithm = "SHA256withECDSA";

ISigner signer = SignerUtilities.GetSigner(signerAlgorithm);
signer.Init(true, privateSigningKey);
signer.BlockUpdate(data, 0, data.Length);
byte[] signature = signer.GenerateSignature();

return signature;

关于c# - 在 C# 中使用 Bouncy CaSTLe 验证 ECDSA 签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37572306/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com