Click here to Skip to main content
15,301,841 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more: , +
Hi all,

In order to access to the web service I need a certificate.

I generated my certs:

openssl genrsa 1024 > private.key
openssl req -new -x509 -nodes -sha1 -days 1100 -key private.key > public.cer

then merged this two into a pfx certificate by

openssl pkcs12 -in public.cer -inkey private.key -export -out client.pfx

then loaded my pfx file as X509Certificate2

X509Certificate2 clientCert = new X509Certificate2("cert.pfx", "password");
Now, I would like to create a table into the data base that contains the
following fields:

PrivateKey NVARCHAR  
PublicCer NVARCHAR  

Then copy the content from private.key file, along with -----BEGIN CERTIFICATE----- and -----END CERTIFICATE-----, same for the public.cer, and set the password. Now, how can I get a proper instance of X509Certificate2 by reading this data from DB? In other words, how can I generate a pfx file from code, based on private key and certificate?

Let see in detail what is done till now.

string connectionString; string query; string cert;

        connectionString = ConfigurationManager.ConnectionStrings[0].ConnectionString;
        query = "SELECT clientcert FROM settings_services WHERE ID = 1";

        using (SqlConnection cn = new SqlConnection(connectionString))
            SqlCommand cmd = new SqlCommand(query, cn);
            cert = (string)cmd.ExecuteScalar();

        X509Certificate2  serverCert = new X509Certificate2(Encoding.UTF8.GetBytes(cert));

This code will correctly load a certificate string (x509 certificate, starting with -----BEGIN CERTIFICATE----- and ending -----END CERTIFICATE-----).

Now I need to get the private key:

My private key is in RSA format (-----BEGIN RSA PRIVATE KEY---- etc...)

I need to load it, and assign it to serverCert, in order to be able to use this certificate for authenticate on web service.

Any suggestions on how to do that?


1 solution

You will find the answer here

Certificates to DB and Back[^]

Hope it helps.


This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900