82 lines
3.4 KiB
C#

using DigitalData.Core.Security.Cryptographer;
namespace DigitalData.Core.Security.Config
{
public class AsymCryptParams : RSAFactoryParams
{
public string PemDirectory { get; init; } = string.Empty;
/// <summary>
/// Represents the separator used to concatenate the components of a file-related token string.
/// </summary>
/// <remarks>
/// The resulting file-related token string is constructed as follows:
/// <c>string.Join(FileNameSeparator, Issuer, Audience, Secret_version)</c>.
/// If <c>Secret_version</c> is not null, it will be included in the concatenation.
/// </remarks>
/// <example>
/// For example, if <c>FileNameSeparator = "_-_"</c>, the output might look like:
/// <c>"Issuer_-_Audience_-_Secret_version"</c>.
/// </example>
public string FileNameSeparator { get; init; } = "_-_";
public string FileExtension { get; init; } = "pem";
/// <summary>
/// Represents the separator used to concatenate the components of a key-related token string.
/// </summary>
/// <remarks>
/// The resulting key-related token string is constructed as follows:
/// <c>string.Join(KeyNameSeparator, Issuer, Audience, Secret_version)</c>.
/// If <c>Secret_version</c> is not null, it will be included in the concatenation.
/// </remarks>
/// <example>
/// For example, if <c>KeyNameSeparator = ":"</c>, the output might look like:
/// <c>"Issuer:Audience:Secret_version"</c>.
/// </example>
public string KeyNameSeparator { get; init; } = ":";
public IEnumerable<RSADecryptor> Decryptors { get; init; } = new List<RSADecryptor>();
public RSADecryptor? Vault { get; init; }
public AsymCryptParams()
{
AfterCreate += () =>
{
// Create root folder if it does not exist
if (!Directory.Exists(PemDirectory))
Directory.CreateDirectory(PemDirectory);
foreach (var decryptor in Decryptors)
{
// set default path
if (decryptor.IsPemNull)
{
var file_name_params = new List<object> { decryptor.Issuer, decryptor.Audience, KeySizeInBits };
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));
}
}
}
};
}
}
}