4

Is there a way to extract the public key from a certificate using C#? I have a certificate file with .crt extension.

HorstKevin
  • 303
  • 2
  • 12
hs2d
  • 6,027
  • 24
  • 64
  • 103

1 Answers1

4

Use:

certificate = new X509Certificate2("server.crt", "secret_password");
byte[] publicKey = certificate.PublicKey.EncodedKeyValue.RawData;

now the 'publicKey' byte array is the ASN.1-encoded representation of the public key value.

Matt
  • 1,953
  • 1
  • 19
  • 42
Teoman Soygul
  • 25,584
  • 6
  • 69
  • 80
  • 1
    `byte[] publicKey = certificate.GetPublicKey.EncodedKeyValue.RawData;` didnt work for me, had to use just `byte[] publicKey = certificate.GetPublicKey();` – hs2d Jun 07 '11 at 18:10
  • well yes, that's more suitable if you're going to make use of the public key directly. – Teoman Soygul Jun 07 '11 at 18:13
  • And how to get public key from bytes? for example, I have public key (generated with EC algorithm, curve "secp256r1") and its encoded bytes on java, How can I create public key from these bytes in c#? – Dadroid Nov 16 '16 at 11:24
  • For what I can see, the _public key info_ you get is actually a `sequence`, which contains among the rest the actual public key. See https://github.com/ajanicij/x509-tutorial/blob/master/x509-analysis.md – Mike Jul 16 '23 at 12:24