using DigitalData.Core.Abstractions.Security; using DigitalData.Core.Security.Config; using DigitalData.Core.Security.Extensions; using System.Security.Cryptography; namespace DigitalData.Core.Security.Cryptographer { public class RSADecryptor : RSACryptographer, IRSADecryptor, IRSACryptographer { public bool Encrypt { get; init; } private readonly Lazy _lazyEncryptor; public IRSAEncryptor Encryptor => _lazyEncryptor.Value; public RSADecryptor() { _lazyEncryptor = new(() => new RSAEncryptor() { Pem = RSA.ExportRSAPublicKeyPem(), Padding = Padding }); } public byte[] Decrypt(byte[] data) => RSA.Decrypt(data, Padding); public string Decrypt(string data) => RSA.Decrypt(data.Base64ToByte(), Padding).BytesToString(); public override void Init() { base.Init(); if (Encrypt) RSA.ImportFromEncryptedPem(Pem, Secrets.PBE_PASSWORD.AsSpan()); else RSA.ImportFromPem(Pem); } public override void FileNotFoundEvent() { var new_decryptor = new RSADecryptor() { Pem = RSAFactory.Static.CreateRSAPrivateKeyPem(), Encrypt = Encrypt }; _pem = new_decryptor.Pem; if (PemPath is not null) Task.Run(async () => { await File.WriteAllTextAsync(_pem, PemPath); }); } } }