46 lines
1.3 KiB
C#
46 lines
1.3 KiB
C#
|
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;
|
|||
|
}
|
|||
|
}
|