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

Viewed 1106

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.

2 Answers

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;
}

In the examples on the ECDsaCng, they have the receiver / your verify

public class Bob
{
    public byte[] key;

    public void Receive(byte[] data, byte[] signature)
    {
        using (ECDsaCng ecsdKey = new ECDsaCng(CngKey.Import(key, CngKeyBlobFormat.EccPublicBlob)))
        {
            if (ecsdKey.VerifyData(data, signature))
                Console.WriteLine("Data is good");
            else
                Console.WriteLine("Data is bad");
        }
    }
} 

My assumption is that your "dsa" can be instantiated with the other overload taking

CngKey.Import(publicKey, CngKeyBlobFormat.EccPublicBlob)

as opposed to creating a new curve.

Related