Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use X509Certificate2 to sign and validate ECDSA-SHA256 signatures

I used OpenSSL to create ECC certificates using SHA256. Now I want to use these certificates to sign data and to validate existing signatures.

I tried using the DSACryptoServiceProvider, but it only supports SHA1 or MD5.

But it seems that ECDsaCng is able to support ECDSA-with-SHA256. The only problem that I have is that I don't know how to convert the Private and Public Key from my X509Certificate2 into the necessary CngKey. I read another question where someone described how to convert the Public Key. But in order to be able to sign data, I need the Private Key, too.

So is there a way to get the CngKey of the Private and Public Key out of the X509Certificate2? The certificates are available in different formats. I have them as PFX file and separately as CER and PEM files.

I would prefer to stick with the .NET Framework 4, but if it's not possible at all to use it, I would also switch to Bouncy Castle.

like image 333
Ryo Shinzo Avatar asked Sep 18 '14 08:09

Ryo Shinzo


1 Answers

Support for this was added in .NET 4.6.1:

private static byte[] SignWithCert(X509Certificate2 cert, byte[] data)
{
    using (ECDsa ecdsa = cert.GetECDsaPrivateKey())
    {
        if (ecdsa == null)
            throw new ArgumentException("Cert must have an ECDSA private key", nameof(cert));

        return ecdsa.SignData(data, HashAlgorithmName.SHA256);
    }
}

private static bool VerifyWithCert(X509Certificate2 cert, byte[] data, byte[] signature)
{
    using (ECDsa ecdsa = cert.GetECDsaPublicKey())
    {
        if (ecdsa == null)
            throw new ArgumentException("Cert must be an ECDSA cert", nameof(cert));

        return ecdsa.VerifyData(data, signature, HashAlgorithmName.SHA256);
    }
}
like image 77
bartonjs Avatar answered Oct 30 '22 03:10

bartonjs