Extract .pub file from a P12 certificate with C#


In cryptographyPKCS #12 defines an archive file format for storing many cryptography objects as a single file. It is commonly used to bundle a private key with its X.509 certificate or to bundle all the members of a chain of trust.

When working with Oauth2 you may find that the client_credentials grant type supports the user of P12 files. For examples Googles service account authencation supports p12 files as well as json key files, within their server to server authencation flow.

You may have need of the prem file or the .pub file. Which contains the public key for your authorization

-----BEGIN PUBLIC KEY-----
...Base64 encoding of the DER encoded certificate...
-----END PUBLIC KEY-----

We can extract that file from the p12 file with the following code.

 var certificate = new X509Certificate2(pathToCert, certPassword,
            X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);


var key = certificate.GetRSAPrivateKey() ;
var pubKeyBytes = key.ExportSubjectPublicKeyInfo();
var privKeyBytes = key.ExportPkcs8PrivateKey();
var pubKeyPem = PemEncoding.Write("PUBLIC KEY", pubKeyBytes);
var privKeyPem = PemEncoding.Write("PRIVATE KEY", privKeyBytes);

var publicKeypub = new string(pubKeyPem);  // save this to a file

Conclusion

In the last 10 years I have only needed to do this a couple of times. I am writing this post more for future me then for anything else. I hope it helps someone


About Linda Lawton

My name is Linda Lawton I have more than 20 years experience working as an application developer and a database expert. I have also been working with Google APIs since 2012 and I have been contributing to the Google .Net client library since 2013. In 2013 I became a a Google Developer Experts for Google Analytics.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.