Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export private key from X509Certificate object

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.

like image 430
RRR Avatar asked Oct 10 '11 13:10

RRR


2 Answers

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

like image 75
poupou Avatar answered Oct 06 '22 04:10

poupou


You can simply use the PrivateKey property of X509Certificate2. The actual returned private key implementation depends on the algorithm used in the certificate - usually this is RSA:

rsaObj = (RSACryptoServiceProvider)myCertificate.PrivateKey; 

Afterwards you should be able to get the RSA key information from it's ExportParameters property.

like image 31
Robert Avatar answered Oct 06 '22 04:10

Robert