Verifying ECDSA signature with Bouncy Castle in C#

不羁的心 提交于 2019-12-06 05:08:59

Instead of DER-encoding the signature by yourself, you can use signer.GenerateSignature() like so:

        var signerAlgorithm = "SHA256withECDSA";

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

        return signature;

dbugger was right. DER encoding is wrong. The code in question should be replaced by:

    private static byte[] derEncodeSignature(byte[] signature)
    {
        byte[] r = signature.RangeSubset(0, (signature.Length / 2));
        byte[] s = signature.RangeSubset((signature.Length / 2), (signature.Length / 2));

        MemoryStream stream = new MemoryStream();
        DerOutputStream der = new DerOutputStream(stream);

        Asn1EncodableVector v = new Asn1EncodableVector();
        v.Add(new DerInteger(new BigInteger(1, r)));
        v.Add(new DerInteger(new BigInteger(1, s)));
        der.WriteObject(new DerSequence(v));

        return stream.ToArray();
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!