Store X509Certificate2 in DB

Is it possible to store X509Certificate2 in a SQL Server table instead of pulling a .p12 file from the file system? I am sure you may not know how to do this.

+7
c # x509certificate
source share
2 answers

It is certainly possible, X509Certificate2 has a RawData property that can be stored in your SQL database. To restore a certificate, you can use this constructor

var cert = new X509Certificate2(filename); var data = cert.RawData; // save data to database... // Fetch data from database... cert = new X509Certificate2(data); 
+8
source share

Use .Export (), then Convert.ToBase64String () and save as NVARCHAR (MAX)

To save it:

 var cert = new X509Certificate2(filename); var stringOfCertWithPrivateKey = Convert.ToBase64String(cert.Export(X509ContentType.Pkcs12)); // Or as a regular cert, which will strip the private key out var stringOfCertWithoutPrivateKey = Convert.ToBase64String(cert.Export(X509ContentType.Cert)); // Save either string as NVARCHAR(MAX) in the DB, it just a string now. 

Then simply restore (after returning from the database) with:

 var certBytes = Convert.FromBase64String(stringOfCertWithPrivateKey); var cert = new X509Certificate2(certBytes); 

Using Export () is better than .RawData, since you can choose whether to keep the private key or not (using .RawData will always deprive it).

+3
source share

All Articles