Take the 2-minute tour ×

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.

share|improve this question
How do you create the certificate? –  Dmitry Shkuropatsky Jan 15 '12 at 5:41
Created using makecert.exe with these switches: -r -pe –  danludwig Jan 15 '12 at 15:44
add comment

2 Answers

up vote 2 down vote accepted

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);
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);

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.

share|improve this answer
add comment

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|improve this answer
I did that, but it would not let me export as anything except pkcs12 (.pfx) –  danludwig Jan 15 '12 at 15:43
add comment

Your Answer


