In cryptography, PKCS #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
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