Export private key from X509Certificate object

RRR picture RRR · Oct 10, 2011 · Viewed 21.6k times · Source

We use C# code we build X509Certificate2 with .p12 file, in the constructor we insert the path to certificate, certificate's password. We also marked it as Exportable as shown below:

X509Certificate2 x509Certificate2 = new X509Certificate2
("...\\MyCerificate.p12", "P@ssw0rd", X509KeyStorageFlags.Exportable);

we get the private key as AsymmetricAlgorithm format by the following:

x509Certificate2.PrivateKey

Now, we want to get the private key from the certificate as Base64 format - but we don't have any idea how to do it, and its so important for us.

Answer

poupou picture poupou · Oct 10, 2011

The important question is why base64 ?

If this is for your own application then you can keep the private key as an XML string (much easier :-).

string xml = x509Certificate2.PrivateKey.ToXmlString (true);

If you want base64 (again just for your application) you can export the key (RSAParameters) then concat every byte[] and turn the merged output to a base64 string.

But if you want to interop with other applications that requires a base64 private key then you need to know the format (inside the base64 string). E.g. in many case private keys are PEM encoded (which is base64 with a special header/footer, see an example for X509Certificate).

If that what's you're looking for then you'll need to encode the private key within a PKCS#8 structure first, then turn in into base64 and add the header/footer. You can find some helpful code to do so inside Mono.Security.dll (MIT.X11 licensed code from the Mono project).