using System; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Options; using StellaOps.Cryptography; using StellaOps.Cryptography.DependencyInjection; using StellaOps.Cryptography.Plugin.CryptoPro; using StellaOps.Cryptography.Plugin.Pkcs11Gost; namespace StellaOps.Configuration; public static class StellaOpsCryptoServiceCollectionExtensions { public static IServiceCollection AddStellaOpsCrypto( this IServiceCollection services, StellaOpsCryptoOptions? options) { ArgumentNullException.ThrowIfNull(services); var resolved = options ?? new StellaOpsCryptoOptions(); services.AddStellaOpsCrypto(registryOptions => { ApplyRegistry(registryOptions, resolved.Registry); }); services.AddPkcs11GostProvider(); services.Configure(target => { CopyPkcs11Options(target, resolved.Pkcs11); }); services.AddCryptoProGostProvider(); services.Configure(target => { CopyCryptoProOptions(target, resolved.CryptoPro); }); services.Configure(hash => { hash.DefaultAlgorithm = string.IsNullOrWhiteSpace(resolved.DefaultHashAlgorithm) ? HashAlgorithms.Sha256 : resolved.DefaultHashAlgorithm.Trim(); }); return services; } private static void ApplyRegistry( CryptoProviderRegistryOptions target, CryptoProviderRegistryOptions source) { target.ActiveProfile = source.ActiveProfile; target.PreferredProviders.Clear(); foreach (var provider in source.PreferredProviders) { if (!string.IsNullOrWhiteSpace(provider)) { target.PreferredProviders.Add(provider.Trim()); } } target.Profiles.Clear(); foreach (var kvp in source.Profiles) { if (kvp.Value is null) { continue; } var profile = new CryptoProviderProfileOptions(); foreach (var provider in kvp.Value.PreferredProviders) { if (!string.IsNullOrWhiteSpace(provider)) { profile.PreferredProviders.Add(provider.Trim()); } } target.Profiles[kvp.Key] = profile; } } private static void CopyPkcs11Options(Pkcs11GostProviderOptions target, Pkcs11GostProviderOptions source) { target.Keys.Clear(); foreach (var key in source.Keys) { target.Keys.Add(key.Clone()); } } private static void CopyCryptoProOptions(CryptoProGostProviderOptions target, CryptoProGostProviderOptions source) { target.Keys.Clear(); foreach (var key in source.Keys) { target.Keys.Add(key.Clone()); } } }