aboutsummaryrefslogtreecommitdiff
path: root/Tools/Hazel-Networking/Hazel/Crypto/DefaultAes.cs
blob: da72fb82e620bbc4a277370aed80be07a71eb21e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
using System;
using System.Security.Cryptography;

namespace Hazel.Crypto
{
    /// <summary>
    /// AES provider using the default System.Security.Cryptography implementation
    /// </summary>
    public class DefaultAes : IAes
    {
        private readonly ICryptoTransform encryptor_;

        /// <summary>
        /// Create a new default instance of the AES block cipher
        /// </summary>
        /// <param name="key">Encryption key</param>
        public DefaultAes(ByteSpan key)
        {
            // Create the AES block cipher
            using (Aes aes = Aes.Create())
            {
                aes.KeySize = key.Length * 8;
                aes.BlockSize = aes.KeySize;
                aes.Mode = CipherMode.ECB;
                aes.Padding = PaddingMode.Zeros;
                aes.Key = key.ToArray();

                this.encryptor_ = aes.CreateEncryptor();
            }
        }

        /// <inheritdoc/>
        public void Dispose()
        {
            this.encryptor_.Dispose();
        }

        /// <inheritdoc/>
        public int EncryptBlock(ByteSpan inputSpan, ByteSpan outputSpan)
        {
            if (inputSpan.Length != outputSpan.Length)
            {
                throw new ArgumentException($"ouputSpan length ({outputSpan.Length}) does not match inputSpan length ({inputSpan.Length})", nameof(outputSpan));
            }

            return this.encryptor_.TransformBlock(inputSpan.GetUnderlyingArray(), inputSpan.Offset, inputSpan.Length, outputSpan.GetUnderlyingArray(), outputSpan.Offset);
        }
    }
}