Store an X509Certificate2 in DB

≡放荡痞女 提交于 2019-12-03 13:59:19
Rohan West

This is definitely possible, the X509Certificate2 has a RawData property that can be saved into your SQL Database. To reconstruct the 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);

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's just a string now.

Then just restore (after getting it back from DB) with:

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

Using Export() is better than .RawData as you can choose to persist the Private key or not (using .RawData will always strip it).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!