Create AesProvider using Aes provided by .Net

This commit is contained in:
Timothy Schenk 2023-01-02 12:18:38 +01:00
parent 84c13cc1ba
commit e3eb36639a

46
Server/AesProvider.cs Normal file
View file

@ -0,0 +1,46 @@
using System.Security.Cryptography;
using Microsoft.Extensions.Logging;
namespace Server;
public class AesProvider
{
private readonly Aes _aes;
private readonly ICryptoTransform _encryptor;
private readonly ICryptoTransform _decryptor;
private readonly ILogger _logger;
public AesProvider(ILoggerFactory loggerFactory, Span<byte> key, Span<byte> iv)
{
_logger = loggerFactory.CreateLogger(nameof(AesProvider));
_aes = Aes.Create();
_aes.Key = key.ToArray();
_aes.IV = iv.ToArray();
_encryptor = _aes.CreateEncryptor();
_decryptor = _aes.CreateDecryptor();
}
public Span<byte> Encrypt(Span<byte> input)
{
using MemoryStream memoryStream = new MemoryStream();
using CryptoStream cryptoStream = new CryptoStream(memoryStream, _encryptor, CryptoStreamMode.Write);
cryptoStream.Write(input);
cryptoStream.Flush();
Span<byte> bytes = memoryStream.ToArray();
return bytes;
}
public Span<byte> Decrypt(Span<byte> input)
{
using MemoryStream memoryStream = new MemoryStream(input.ToArray());
using CryptoStream cryptoStream = new CryptoStream(memoryStream, _decryptor, CryptoStreamMode.Read);
Span<byte> bytes = new byte[input.Length];
var i = cryptoStream.Read(bytes);
if (i > 0)
_logger.LogWarning("CryptoStream hasn't been read till the end. ({length}", i);
return bytes;
}
}