using DigitalData.Core.Abstractions.Security; using System.Security.Cryptography; namespace DigitalData.Core.Security.Cryptographer { public class RSACryptographer : IRSACryptographer { private string? _pem; public string Pem { get => _pem ?? throw new InvalidOperationException($"Pem is not initialized. Please ensure that the PEM is set or properly loaded from the file. Issuer: {Issuer}, Audience: {Audience}."); init => _pem = value; } public string? PemPath => FileName is null ? null : Path.Combine(Directory, FileName); public string Directory { get; set; } = string.Empty; public string? FileName { get; set; } public RSAEncryptionPadding Padding { get; init; } = RSAEncryptionPadding.OaepSHA256; protected virtual RSA RSA { get; } = RSA.Create(); public string Issuer { get; init; } = string.Empty; public string Audience { get; init; } = string.Empty; internal RSACryptographer() { } public virtual void UnableToInitPemEvent() => throw new InvalidOperationException( $"Pem is not initialized and pem file is null. Issuer is {Issuer} and audience {Audience}."); public virtual void FileNotFoundEvent() => throw new FileNotFoundException( $"Pem is not initialized and pem file is not found in {PemPath}. Issuer is {Issuer} and audience {Audience}."); // TODO: make file read asynchronous, consider multiple routing public virtual void Init() { if(_pem is null) { if(PemPath is null) UnableToInitPemEvent(); if (File.Exists(PemPath)) _pem = File.ReadAllText(PemPath); else FileNotFoundEvent(); } } } }