58 lines
1.6 KiB
C#
58 lines
1.6 KiB
C#
using DigitalData.Core.Abstractions.Security;
|
|
using DigitalData.Core.Security.Extensions;
|
|
using System.Security.Cryptography;
|
|
|
|
namespace DigitalData.Core.Security.Cryptographer
|
|
{
|
|
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<IRSAEncryptor> _lazyEncryptor;
|
|
|
|
public IRSAEncryptor Encryptor => _lazyEncryptor.Value;
|
|
|
|
private readonly Lazy<RSA> 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();
|
|
}
|
|
} |