Store an X509Certificate2 in DB

元气小坏坏 提交于 2019-12-13 11:43:17

问题


Is it possible to store an X509Certificate2 in a SQL Server table rather than pull a .p12 file from the file system? I'm sure you can but not sure how to go about this.


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/2240176/store-an-x509certificate2-in-db

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