using DigitalData.Core.Abstractions.Security; using DigitalData.Core.Security.Config; using DigitalData.Core.Security.Cryptographer; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Options; using System.Text.Json; using System.Text.Json.Serialization; namespace DigitalData.Core.Security { public static class DIExtensions { public static JsonSerializerOptions AddCryptographerConverter(this JsonSerializerOptions options) { if (!options.Converters.OfType().Any()) options.Converters.Add(new HashAlgorithmNameConverter()); if (!options.Converters.OfType().Any()) options.Converters.Add(new JsonStringEnumConverter()); return options; } private static IServiceCollection AddAsymCryptService(this IServiceCollection services) where TAsymCryptParams : AsymCryptParams { services.TryAddScoped, AsymCryptService>(); return services; } public static IServiceCollection AddAsymCryptService(this IServiceCollection services, IConfigurationSection section) where TAsymCryptParams : AsymCryptParams => services.Configure(section).AddAsymCryptService(); public static IServiceCollection AddAsymCryptService(this IServiceCollection services, TAsymCryptParams param) where TAsymCryptParams : AsymCryptParams => services.AddSingleton(Options.Create(param)).AddAsymCryptService(); /// /// Registers default RSA Factory instance with default params /// /// /// public static IServiceCollection AddRSAFactory(this IServiceCollection services) { services.TryAddScoped(_ => Instance.RSAFactory); return services; } /// /// Registers a custom RSA Factory instance with specified parameters from the given configuration section. /// /// /// /// /// public static IServiceCollection AddRSAFactory(this IServiceCollection services, IConfigurationSection section) where TRSAFactoryParams : RSAFactoryParams { services.Configure(section); services.TryAddSingleton, RSAFactory>(); return services; } /// /// Registers an RSA Factory with the specified parameters from the given instance. Optionally, sets it as the default factory. /// /// The type of the RSA factory parameters. /// /// /// If true, the factory is registered as the default . Otherwise, it is registered as . /// The updated with the RSA Factory registered. public static IServiceCollection AddRSAFactory(this IServiceCollection services, TRSAFactoryParams rsaParams, bool setAsDefault = false) where TRSAFactoryParams : RSAFactoryParams { services.TryAddSingleton(Options.Create(rsaParams)); if (setAsDefault) services.TryAddSingleton>(); else services.TryAddSingleton, RSAFactory>(); return services; } } }