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 key, Span 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 Encrypt(Span input) { using MemoryStream memoryStream = new MemoryStream(); using CryptoStream cryptoStream = new CryptoStream(memoryStream, _encryptor, CryptoStreamMode.Write); cryptoStream.Write(input); cryptoStream.Flush(); Span bytes = memoryStream.ToArray(); return bytes; } public Span Decrypt(Span input) { using MemoryStream memoryStream = new MemoryStream(input.ToArray()); using CryptoStream cryptoStream = new CryptoStream(memoryStream, _decryptor, CryptoStreamMode.Read); Span 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; } }