据我所知,如果你想将证书读入内存缓存,你可以创建一个包含 GetRSAPublicKey() 和 GetRSAPrivateKey() 方法的服务。
在每种方法中,都会尝试从内存缓存中获取证书,如果内存缓存存在,则会从内存中读取。
在我看来,将信息存储到服务器内存中就足够安全了。
更多细节,您可以参考以下代码:
IGetCertificate 接口:
public interface IGetCertificate
{
public string GetRSAPublicKey();
public string GetRSAPrivateKey();
}
获取证书:
public class GetCertificate : IGetCertificate
{
private IMemoryCache _cache;
public GetCertificate(IMemoryCache memoryCache) {
_cache = memoryCache;
}
public string GetRSAPrivateKey()
{
string result;
if (!_cache.TryGetValue("TestKey", out result))
{
X509Store store = new X509Store(StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection cers = store.Certificates.Find(X509FindType.FindBySubjectName, "localhost", false);
if (cers.Count > 0)
{
var cer = cers[0];
string re = cer.PrivateKey.ToXmlString(false);
_cache.Set("TestKey", re);
return re;
}
else {
return "Couldn't find the certificate";
};
}
else {
return result;
}
}
public string GetRSAPublicKey()
{
string result;
if (!_cache.TryGetValue("TestPubkcKeyOID", out result))
{
X509Store store = new X509Store(StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection cers = store.Certificates.Find(X509FindType.FindBySubjectName, "localhost", false);
if (cers.Count > 0)
{
var cer = cers[0];
string re = cer.PublicKey.Oid.Value;
_cache.Set("TestPubkcKeyOID", re);
return re;
}
else
{
return "Couldn't find the certificate";
};
}
else
{
return result;
}
}
}
注册服务:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddMemoryCache();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Dotnet5WebAPIApplication", Version = "v1" });
});
services.AddScoped(typeof(IGetCertificate),typeof(GetCertificate));
}
用法:
public WeatherForecastController(ILogger<WeatherForecastController> logger, IGetCertificate getCertificate)
{
_logger = logger;
_getCertificate = getCertificate;
}
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
var re = _getCertificate.GetRSAPrivateKey();
var re2 = _getCertificate.GetRSAPublicKey();
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}