using DigitalData.Core.Abstractions.Security; using DigitalData.Core.Security.Cryptographer; namespace DigitalData.Core.Security.Config { public class AsymCryptParams : RSAFactoryParams { public string PemDirectory { get; init; } = string.Empty; /// /// Represents the separator used to concatenate the components of a file-related token string. /// /// /// The resulting file-related token string is constructed as follows: /// string.Join(FileNameSeparator, Issuer, Audience, Secret_version). /// If Secret_version is not null, it will be included in the concatenation. /// /// /// For example, if FileNameSeparator = "_-_", the output might look like: /// "Issuer_-_Audience_-_Secret_version". /// public string FileNameSeparator { get; init; } = "_-_"; public string FileExtension { get; init; } = "pem"; /// ///This is the subtext of the pem file name. For the file to be automatically renewed, the name must be assigned to change periodically. For example, by default MM/2 will be refreshed every 2 months. ///
/// - is used when converting to tag. ///
/// - If the format contains the symbol “//”, the method divides the numeric value obtained from the left side of the format /// by one minus the numeric value obtained from the right side of the format string and adds one. For instance: ///
/// - If the date is 02.03.2024 and the format is "MM//2", it extracts the month (02), subtracts one (3), divides it by 2, /// rounds down the outgoing number (1), adds one to the number (resulting in 2). ///
/// - If the format does not contain "//", the method uses the default format. ///
/// This method provides a way to format the date based on typical or customized rules, including mathematical operations like division. ///
public string DateTagFormat { get; init; } = "MM//2"; public IEnumerable PrivateKeys { get; init; } = new List(); public RSAPrivateKey? VaultPrivateKey { get; init; } public AsymCryptParams() { // init decryptors AfterCreate += () => { // Create root folder if it does not exist if (!Directory.Exists(PemDirectory)) Directory.CreateDirectory(PemDirectory); foreach (var decryptor in PrivateKeys) { // set default path if (decryptor.IsPemNull) { var file_name_params = new List { decryptor.Issuer, decryptor.Audience, KeySizeInBits, DateTime.Now.ToTag(DateTagFormat) }; if (decryptor.IsEncrypted) file_name_params.Add(Secrets.Version); var file_name = $"{string.Join(FileNameSeparator, file_name_params)}.{FileExtension}"; var path = Path.Combine(PemDirectory, file_name); if (File.Exists(path)) decryptor.SetPem(File.ReadAllText(path)); else { var pem = decryptor.IsEncrypted ? Instance.RSAFactory.CreateEncryptedPrivateKeyPem(pbeParameters: PbeParameters, keySizeInBits: KeySizeInBits, password: Secrets.PBE_PASSWORD) : Instance.RSAFactory.CreatePrivateKeyPem(keySizeInBits: KeySizeInBits); decryptor.SetPem(pem); // Save file in background Task.Run(async () => await File.WriteAllTextAsync(path: path, pem)); } } } }; } } }