Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 258
danludwig Avatar asked Jan 14 '12 17:01

danludwig


People also ask

How do I decode encrypted base64?

To decode with base64 you need to use the --decode flag. With encoded string, you can pipe an echo command into base64 as you did to encode it. Using the example encoding shown above, let's decode it back into its original form. Provided your encoding was not corrupted the output should be your original string.


2 Answers

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.

like image 62
danludwig Avatar answered Nov 13 '22 06:11

danludwig


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.

like image 37
Dmitry Shkuropatsky Avatar answered Nov 13 '22 06:11

Dmitry Shkuropatsky