Create AesProvider using Aes provided by .Net
This commit is contained in:
parent
84c13cc1ba
commit
e3eb36639a
1 changed files with 46 additions and 0 deletions
46
Server/AesProvider.cs
Normal file
46
Server/AesProvider.cs
Normal 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;
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue