47 lines
1.3 KiB
C#
47 lines
1.3 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
|
|
};
|
|
}
|
|
}
|
|
|
|
internal RSADecryptor() { }
|
|
|
|
[OnDeserialized]
|
|
private void OnDeserialized(StreamingContext context) => Init();
|
|
|
|
private IRSADecryptor Init()
|
|
{
|
|
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());
|
|
|
|
return this;
|
|
}
|
|
|
|
public byte[] Decrypt(byte[] data) => _rsa.Decrypt(data, Padding);
|
|
|
|
public string Decrypt(string data) => _rsa.Decrypt(data.Base64ToByte(), Padding).BytesToString();
|
|
}
|
|
} |