How to get the base 64 encoded value of a certificate with private key?

19,693

Solution 1

I was unable to figure out how to do this with mmc. However I did figure out how to do it in code:

var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
var certificate = store.Certificates.Find(X509FindType.FindByThumbprint, 
    "BLABLABLA", false)[0]; // doesn't matter how you get the cert
var exported = certificate.Export(X509ContentType.Pfx, "the password");
var base64 = Convert.ToBase64String(exported);
store.Close();

As long as the cert you are getting from the x 509 store has the private key, it will end up in the exported byte arrray, which you can then convert to a base64 string.

Solution 2

Make sure you mark private key as exportable when you add the certificate to the store.

If you use makecert to create the certificate, add -pe option to make private key exportable.

Share:
19,693
danludwig
Author by

danludwig

System Fragmentation Advocate, Cloud Services Puppeteer, & Network Parsimony Policeman AWS Certified Developer Associate 2021

Updated on June 18, 2022

Comments

  • danludwig
    danludwig almost 2 years

    Follow up to a previous question, I have some code that needs to get an X509 certificate with a private key. As noted in the answers, in production this will happen using X509Store.

    What is the best way to unit test this? I want to develop and test with different certificates than will be in production, so I could create a CertificateRepository interface to provide different implementations.

    For the test / dev implementation, it would be nice to just use a base64 encoded string of the certificate, and create a cert instance that way, with a dummy password and dedicated test / dev cert. However so far I have been unable to figure out how to encode a certificate with private key as a base64 string. Each time I try to export the cert from MMC as base-64, it encodes the public key only.

  • danludwig
    danludwig over 12 years
    I did that, but it would not let me export as anything except pkcs12 (.pfx)