问题
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