Search code examples
c#.net-coreecdsa

.NET Core - How to verfiy a ECDSA signature with named curve


I try to verfiy a signature with the named curve secP256k1 and a public key in a byte array. I don't know how to add the public key to my ECDsaCng object. The hash of the data is a SHA256 hash.

static byte[] publicKey = new byte[] {
    0x04, 0xD3, ..., 0x20
};

public static bool VerifySignature(byte[] hash, byte[] signature)
{
    using (ECDsaCng dsa = new ECDsaCng(ECCurve.CreateFromFriendlyName("secP256k1")))
    {
        // How to add the public key?

        bool result = dsa.VerifyHash(hash, signature);

        return result;
    }
}

I tried to use ImportSubjectPublicKeyInfo, but I get the exception "ASN1 corrupted data"

public static bool VerifySignature(byte[] hash, byte[] signature)
{
    using (ECDsaCng dsa = new ECDsaCng(ECCurve.CreateFromFriendlyName("secP256k1")))
    {
        int bytesRead;

        dsa.ImportSubjectPublicKeyInfo(publicKey, out bytesRead);

        bool result = dsa.VerifyHash(hash, signature);

        return result;
    }
}

I hope anyone have an idea to solve the problem or could show me a different way.


Solution

  • My solution looks like this:

    public static bool VerifySignature(byte[] hash, byte[] signature)
    {
        var dsa = ECDsa.Create(new ECParameters
        {
            Curve = ECCurve.CreateFromFriendlyName("secP256k1"),
            Q =
            {
                X = publicKey.Take(32).ToArray(),
                Y = publicKey.Skip(32).ToArray()
            }
        });
    
        bool result = dsa.VerifyHash(hash, signature);
    
        return result;
    }