Export secret key from X509Certificate object

We use C # code, which we create X509Certificate2 with a .p12 file, in the constructor we insert the path to the certificate, certificate 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 an asymmetric algorithm format as follows:

 x509Certificate2.PrivateKey 

Now we want to get the private key from the certificate in Base64 format, but we don’t know how to do it, and it is so important for us.

+7
source share
3 answers

An important question: why base64 ?

If this is for your own application, you can save the private key as an XML string (much simpler :-).

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

If you want base64 (again for your application), you can export the key (RSAParameters), then concat each byte[] and turn the combined output into a base64 string.

But if you want to interact with other applications that require a base64 private key, you need to know the format (inside the base64 string). For example. in many cases, PEM private keys are encoded (this is base64 with a special header / footer, see example for X509Certificate ).

If this is what you are looking for, you need to first encode the private key in the PKCS # 8 structure, then rotate to base64 and add a header / footer. You can find useful code to do this inside Mono.Security.dll (license code MIT.X11 from the Mono project).

+3
source

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

 rsaObj = (RSACryptoServiceProvider)myCertificate.PrivateKey; 

After that, you will need to get the RSA key information from this ExportParameters property.

+2
source

If your only problem is getting the Base64 private key, you can simply do this:

 var privateKey = x509Certificate2.PrivateKey; var encoding = new System.Text.ASCIIEncoding(); var base64String = Convert.ToBase64String(encoding.GetBytes(privateKey.ToString())); 
-3
source

All Articles