Catalogger.NET/Catalogger.Backend/Database/EncryptionService.cs
2024-08-13 13:08:50 +02:00

36 lines
No EOL
989 B
C#

using System.Security.Cryptography;
using System.Text;
namespace Catalogger.Backend.Database;
public class EncryptionService(Config config) : IEncryptionService
{
private readonly byte[] _secretKey = Convert.FromBase64String(config.Database.EncryptionKey);
public byte[] Encrypt(string data)
{
using var aes = Aes.Create();
aes.Key = _secretKey;
var output = new List<byte>();
output.AddRange(aes.IV);
var plaintext = Encoding.UTF8.GetBytes(data);
var ciphertext = aes.EncryptCbc(plaintext, aes.IV);
output.AddRange(ciphertext);
return output.ToArray();
}
public string Decrypt(byte[] input)
{
using var aes = Aes.Create();
aes.Key = _secretKey;
var iv = input.Take(aes.IV.Length).ToArray();
var ciphertext = input.Skip(aes.IV.Length).ToArray();
var plaintext = aes.DecryptCbc(ciphertext, iv);
return Encoding.UTF8.GetString(plaintext);
}
}