Restructure solution layout by module
This commit is contained in:
@@ -0,0 +1,66 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Security.Cryptography;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
|
||||
namespace StellaOps.Registry.TokenService.Security;
|
||||
|
||||
internal static class SigningKeyLoader
|
||||
{
|
||||
public static SigningCredentials Load(RegistryTokenServiceOptions.SigningOptions options)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
|
||||
SecurityKey key;
|
||||
|
||||
var extension = Path.GetExtension(options.KeyPath);
|
||||
if (string.Equals(extension, ".pfx", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
key = LoadFromPfx(options.KeyPath, options.KeyPassword);
|
||||
}
|
||||
else
|
||||
{
|
||||
key = LoadFromPem(options.KeyPath);
|
||||
}
|
||||
|
||||
var credentials = new SigningCredentials(key, SecurityAlgorithms.RsaSha256)
|
||||
{
|
||||
CryptoProviderFactory = new CryptoProviderFactory { CacheSignatureProviders = true }
|
||||
};
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(options.KeyId))
|
||||
{
|
||||
credentials.Key.KeyId = options.KeyId;
|
||||
}
|
||||
|
||||
return credentials;
|
||||
}
|
||||
|
||||
private static SecurityKey LoadFromPfx(string path, string? password)
|
||||
{
|
||||
using var cert = X509CertificateLoader.LoadPkcs12FromFile(path, password, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.EphemeralKeySet);
|
||||
if (!cert.HasPrivateKey)
|
||||
{
|
||||
throw new InvalidOperationException($"Certificate '{path}' does not contain a private key.");
|
||||
}
|
||||
|
||||
if (cert.GetRSAPrivateKey() is not RSA rsa)
|
||||
{
|
||||
throw new InvalidOperationException($"Certificate '{path}' does not contain an RSA private key.");
|
||||
}
|
||||
|
||||
var parameters = rsa.ExportParameters(true);
|
||||
rsa.Dispose();
|
||||
|
||||
return new RsaSecurityKey(parameters) { KeyId = cert.Thumbprint };
|
||||
}
|
||||
|
||||
private static SecurityKey LoadFromPem(string path)
|
||||
{
|
||||
using var rsa = RSA.Create();
|
||||
var pem = File.ReadAllText(path);
|
||||
rsa.ImportFromPem(pem);
|
||||
return new RsaSecurityKey(rsa.ExportParameters(includePrivateParameters: true));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user