55 lines
1.6 KiB
C#
55 lines
1.6 KiB
C#
using DigitalData.Core.Abstractions.Security;
|
|
using DigitalData.Core.Security.Config;
|
|
using DigitalData.Core.Security.Extensions;
|
|
using System.Security.Cryptography;
|
|
|
|
namespace DigitalData.Core.Security.Cryptographer
|
|
{
|
|
public class RSADecryptor : RSACryptographer, IRSADecryptor, IRSACryptographer
|
|
{
|
|
public bool Encrypt { get; init; }
|
|
|
|
private readonly Lazy<IRSAEncryptor> _lazyEncryptor;
|
|
|
|
public IRSAEncryptor Encryptor => _lazyEncryptor.Value;
|
|
|
|
public RSADecryptor()
|
|
{
|
|
_lazyEncryptor = new(() => new RSAEncryptor()
|
|
{
|
|
Pem = RSA.ExportRSAPublicKeyPem(),
|
|
Padding = Padding
|
|
});
|
|
}
|
|
|
|
public byte[] Decrypt(byte[] data) => RSA.Decrypt(data, Padding);
|
|
|
|
public string Decrypt(string data) => RSA.Decrypt(data.Base64ToByte(), Padding).BytesToString();
|
|
|
|
public override void Init()
|
|
{
|
|
base.Init();
|
|
if (Encrypt)
|
|
RSA.ImportFromEncryptedPem(Pem, Secrets.PBE_PASSWORD.AsSpan());
|
|
else
|
|
RSA.ImportFromPem(Pem);
|
|
}
|
|
|
|
public override void FileNotFoundEvent()
|
|
{
|
|
var new_decryptor = new RSADecryptor()
|
|
{
|
|
Pem = RSAFactory<RSAFactoryParams>.Static.CreateRSAPrivateKeyPem(),
|
|
Encrypt = Encrypt
|
|
};
|
|
|
|
_pem = new_decryptor.Pem;
|
|
|
|
if (PemPath is not null)
|
|
Task.Run(async () =>
|
|
{
|
|
await File.WriteAllTextAsync(_pem, PemPath);
|
|
});
|
|
}
|
|
}
|
|
} |