2

This is a newbie question. I'm trying to load a .der certificate using:

X509Certificate2 cert = new X509Certificate2(@"c:\temp\mycert.der");
RSACryptoServiceProvider csp = (RSACryptoServiceProvider)cert.PublicKey.Key

But I get a "The certificate key algorithm is not supported" error on the 2nd line. When I import this certificate to MMC I can see the public key like this.

Is it valid? How do I get it in code?

2
  • Public key for ECC has different structure than RSA key but windows doesn't display it well. I would use bouncy castle to get the public key out.
    – pepo
    Commented Sep 30, 2015 at 21:13
  • 1
    @pepo, actually, it is not quite correct statement about ECC. Windows supports and correctly displays ECC public keys. The problem is with a curve used in this certificate. Windows supports only a subset of ECC curves and this one is not supported.
    – Crypt32
    Commented Oct 1, 2015 at 2:54

1 Answer 1

4

Prior to .NET 4.6.1 ECDSA keys were not supported. For legacy/compatibility reasons (such as your sample here where you're converting to an RSACryptoServiceProvider) the PublicKey.Key property and X509Certificate2.PrivateKey property still cannot ECDSA. There's instead a new, more type-safe, path:

using (ECDsa ecdsa = cert.GetECDsaPublicKey())
{
    if (ecdsa != null)
    {
        // I had to do something with it in this example...
        bool verified = ecdsa.VerifyData(data, signature, HashAlgorithmName.SHA256);
    }
}
2
  • Ok, but how can I Encrypt() with it?
    – oo_dev
    Commented Nov 11, 2021 at 15:17
  • 1
    @oo_dev ECDSA is a signature algorithm, not an encryption algorithm. Structurally similar keys can be used for EC Diffie-Hellman, and .NET 6 added GetECDiffieHellman{Public|Private}Key(). With ECDH you’d want something called ECIES. But that’s a long answer, so if you (think you) need that, then you should ask a new question if this comment doesn’t have enough data for you to hunt down answers independently.
    – bartonjs
    Commented Nov 11, 2021 at 15:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.