using DigitalData.Core.Abstractions.Security; using DigitalData.Core.Security.Extensions; using System.Security.Cryptography; namespace DigitalData.Core.Security { public class RSADecryptor : RSACryptographer, IRSADecryptor, IRSACryptographer { public string? Password { get; init; } public bool HasEncryptedPem => Password is not null; public bool IsEncrypted => Password is not null; private readonly Lazy _lazyEncryptor; public IRSAEncryptor Encryptor => _lazyEncryptor.Value; private readonly Lazy lazyRSA; protected override RSA RSA => lazyRSA.Value; public RSADecryptor() { _lazyEncryptor = new(() => new RSAEncryptor() { Pem = RSA.ExportRSAPublicKeyPem(), Padding = Padding }); lazyRSA = new(() => { var rsa = RSA.Create(); if (Password is null) RSA.ImportFromPem(Pem); else RSA.ImportFromEncryptedPem(Pem, Password.AsSpan()); return rsa; }); } public byte[] Decrypt(byte[] data) => RSA.Decrypt(data, Padding); public string Decrypt(string data) => RSA.Decrypt(data.Base64ToByte(), Padding).BytesToString(); } }