Search code examples
c#public-key-encryptionecdsa

How to get a public key from ECDsa in C#


In C# I can create an RSA public/private key pair...

RSA rsa = RSA.Create();

byte[] priKey = rsa.ExportRSAPrivateKey();
byte[] pubKey = rsa.ExportRSAPublicKey();

Now I want to do effectively the same thing using ECDsa...

ECDsa ecdsa = ECDsa.Create();

byte[] priKey = ecdsa.ExportECPrivateKey();
...

...but I can't seem to find a method allowing the public key to be exported?


Solution

  • I think you're looking for ExportSubjectPublicKeyInfo()

    var publicKey = ecdsa.ExportSubjectPublicKeyInfo();
    

    The docs say:

    Exports the public-key portion of the current key in the X.509 SubjectPublicKeyInfo format

    Found about "SubjectPublicKeyInfo" source

    The Subject Public Key Info (SubjectPublicKeyInfo) field carries the Public Key component of its associated subject, as well as an indication of the algorithm, and any algorithm parameters, with which the public component is to be used.

    PS: there is also a TryExportSubjectPublicKeyInfo