0

I only have a private key in a pem file and need to extract the public key from it.

At the moment I'm using openssl for this:

openssl rsa -pubout -outform DER

Ho can I do the same in c# (and Bouncycastle)?

  • Huh? That's not the one I wanted to post *at all*. Sorry about that, try the link [here](http://stackoverflow.com/a/26948066/589259). My apologies for the weird link. Would you be helped with [this answer](http://stackoverflow.com/a/26948066/589259) and then just setting the modulus and public exponent? <- redo from start. – Maarten Bodewes Jul 31 '15 at 10:33
  • I'm thinking in the direction of reading the PEM with Bouncy Castle and then using `RSAParameters` to generate the public key. If you also want to use Bouncy to perform the RSA operation then you are already done on step 1 of course. – Maarten Bodewes Jul 31 '15 at 10:43

2 Answers2

-1

In windows world file that contains private key is called PFX.
So you can try to import certificate to collection using .net System.Security.Cryptography infrastructure:

X509Certificate2Collection collection = new X509Certificate2Collection();
collection.Import(filePath, password, X509KeyStorageFlags.PersistKeySet);

The code block was taken from here:
How to retrieve certificates from a pfx file with c#?

Community
  • 1
  • 1
FireAlkazar
  • 1,795
  • 1
  • 14
  • 27
  • I have a pem file, which contains only the private key. – Louis Haußknecht Jul 31 '15 at 09:36
  • @LouisHaußknecht as far as I know a pem file is a container specifically formatted and includes a certificate. So public key should be in. – FireAlkazar Jul 31 '15 at 10:00
  • @LouisHaußknecht and by the way, try to open pem file in a text editor. It is possible to see the structure, at least I can see -----BEGIN CERTIFICATE----- and -----END CERTIFICATE----- in my test file, so even new X509Certificate2(filePath) would work to get public key. – FireAlkazar Jul 31 '15 at 10:12
  • @FireAlkazar Again, I only have a pem file with a private key. – Louis Haußknecht Jul 31 '15 at 10:27
  • @LouisHaußknecht ok, not expecting simple solution then: http://stackoverflow.com/a/10216712/1479335 – FireAlkazar Jul 31 '15 at 11:05
-2

If your .pem file already contains the public key it is usually between the Lines

-----BEGIN PUBLIC KEY-----

and

-----END PUBLIC KEY-----

of the pem file.

At least Openssl does it like this, but you should check it carefully. See this link for an overview over the structure of a pem file.

So you could get it by using the Substring method. This should work:

static void ExtractPublicKeyFromPem(string path)
    {
        var startText = "-----BEGIN PUBLIC KEY-----";
        var endText = "-----END PUBLIC KEY-----";

        var pem = System.IO.File.ReadAllText(path);
        var start = pem.LastIndexOf(startText);
        var end = pem.IndexOf(endText);

        var publicKey = pem.Substring(start, end - start);
    }

Hope it helps :)

Rafael Regh
  • 443
  • 5
  • 17