using DigitalData.Core.Abstractions.Security; using DigitalData.Core.Security.DigitalData.Core.Security; using DigitalData.Core.Security.Extensions; using System.Security.Cryptography; namespace DigitalData.Core.Security { public class RSADecryptor : RSACryptographer, IRSADecryptor, IRSACryptographer { public (string Value, Version Version)? VersionedPassword { init { _password = value?.Value; PasswordVersion = value?.Version; } } private string? _password; public Version? PasswordVersion { get; private init; } = null; 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 override CryptKeyType KeyType => IsEncrypted ? CryptKeyType.EncryptedPrivate : CryptKeyType.Private; 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(); } }