开发者

Store an X509Certificate2 in DB

开发者 https://www.devze.com 2022-12-20 06:35 出处:网络
Is it possible to store an X509Certificate2 in a SQL Server table rather than pull a .p12 开发者_JS百科file from the file system?I\'m sure you can but not sure how to go about this.This is definitely

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


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 VARCHAR(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 VARCHAR(MAX) in the DB, it's just a Base64/ASCII 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).

You can store the result Base64 string in an sql database as a VARCHAR(MAX) type, because Base64 string comprise of only ASCII characters (Thanks to this answer)

0

精彩评论

暂无评论...
验证码 换一张
取 消