From e3eb36639aaeb83dd58e31324542265218d1b05b Mon Sep 17 00:00:00 2001 From: Timothy Schenk Date: Mon, 2 Jan 2023 12:18:38 +0100 Subject: [PATCH] Create AesProvider using Aes provided by .Net --- Server/AesProvider.cs | 46 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Server/AesProvider.cs diff --git a/Server/AesProvider.cs b/Server/AesProvider.cs new file mode 100644 index 0000000..717ac24 --- /dev/null +++ b/Server/AesProvider.cs @@ -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 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; + } +} \ No newline at end of file