This is some example code that loads certs from the certificate store. If this is unavailable to you then you just need to serialise and persist the certificate(s) you need some other way but that ultimately yields a valid X509Certificate2 instance that you can pass into X509SecurityKey.
private static void ConfigureSigningCerts(IServiceCollection services)
{
var keys = new List<SecurityKey>();
var name = "MyCertName";
//The one that expires last at the top
var certs = X509.LocalMachine.My.SubjectDistinguishedName.Find("CN=" + name, false)
.Where(o => DateTime.UtcNow >= o.NotBefore)
.OrderByDescending(o => o.NotAfter);
if (!certs.Any()) throw new Exception("No valid certificates could be found.");
//Get first (in desc order of expiry) th
var signingCert = certs.FirstOrDefault();
if (signingCert == null) throw new InvalidOperationException("No valid signing certificate could be found.");
var signingCredential = new SigningCredentials(new X509SecurityKey(signingCert), "RS256");
services.AddSingleton<ISigningCredentialStore>(new DefaultSigningCredentialsStore(signingCredential));
foreach (var cert in certs)
{
var validationCredential = new SigningCredentials(new X509SecurityKey(cert), "RS256");
keys.Add(validationCredential.Key);
}
services.AddSingleton<IValidationKeysStore>(new DefaultValidationKeysStore(keys));
}
The constructor for X509Certificate2 can take a raw byte[] or a file path so you've got plenty of options when it comes to packaging and distributing the signing/validation certs.
To create a self signed certificate on windows you can use the command:
makecert -r -pe -n "CN=MyCertName" -b 01/01/2015 -e 01/01/2039 -eku 1.3.6.1.5.5.7.3.3 -sky signature -a sha256 -len 2048 mycert.cer
That creates a certificate named MyCertName
in a file called mycert.cer
.
Full docs for the tool here: https://msdn.microsoft.com/en-us/library/bfsktky3(VS.100).aspx
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…