55 lines
1.5 KiB
C#

using DigitalData.Core.Abstractions.Security;
using DigitalData.Core.Security.Extensions;
using System.Runtime.Serialization;
namespace DigitalData.Core.Security
{
public class RSADecryptor : RSACryptographer, IRSADecryptor, IRSACryptographer
{
public string? Password { get; init; }
public bool IsEncrypted => Password is not null;
public IRSAEncryptor Encryptor
{
get
{
return new RSAEncryptor()
{
Pem = _rsa.ExportRSAPublicKeyPem(),
Padding = Padding
};
}
}
public RSADecryptor() { }
public RSADecryptor(string pem, string? password = null)
{
Pem = pem;
Password = password;
Initialize();
}
[OnDeserialized]
private void OnDeserialized(StreamingContext context)
{
Initialize();
}
private void Initialize()
{
if (string.IsNullOrWhiteSpace(Pem))
throw new InvalidOperationException("Pem cannot be null or empty.");
if (Password is null)
_rsa.ImportFromPem(Pem);
else
_rsa.ImportFromEncryptedPem(Pem, Password.AsSpan());
}
public byte[] Decrypt(byte[] data) => _rsa.Decrypt(data, Padding);
public string Decrypt(string data) => _rsa.Decrypt(data.Base64ToByte(), Padding).BytesToString();
}
}