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?

notlkk
  • 1,231
  • 2
  • 23
  • 40
  • 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 Sep 30 '15 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 Oct 01 '15 at 02:54

1 Answers1

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);
    }
}
bartonjs
  • 30,352
  • 2
  • 71
  • 111
  • Ok, but how can I Encrypt() with it? – oo_dev Nov 11 '21 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 Nov 11 '21 at 15:56