aboutsummaryrefslogtreecommitdiffstats
path: root/src/slskd/Common/Cryptography/Aes.cs
blob: 9828d7f8f83d0d791f11bac6dc89f465e8dcdfef (plain) (blame)
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
// <copyright file="Aes.cs" company="slskd Team">
//     Copyright (c) slskd Team. All rights reserved.
//
//     This program is free software: you can redistribute it and/or modify
//     it under the terms of the GNU Affero General Public License as published
//     by the Free Software Foundation, either version 3 of the License, or
//     (at your option) any later version.
//
//     This program is distributed in the hope that it will be useful,
//     but WITHOUT ANY WARRANTY; without even the implied warranty of
//     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//     GNU Affero General Public License for more details.
//
//     You should have received a copy of the GNU Affero General Public License
//     along with this program.  If not, see https://www.gnu.org/licenses/.
// </copyright>

namespace slskd.Cryptography
{
    using System;
    using System.IO;
    using System.Linq;
    using System.Security.Cryptography;

    /// <summary>
    ///     AES utility methods.
    /// </summary>
    public static class Aes
    {
        private static readonly int BlockSizeInBits = 128;
        private static readonly int BlockSizeInBytes = BlockSizeInBits / 8;
        private static readonly int KeySizeInBits = 256;
        private static readonly int KeySizeInBytes = KeySizeInBits / 8;

        /// <summary>
        ///     Decrypts the specified <paramref name="encryptedBytes"/> with the specified <paramref name="key"/>.
        /// </summary>
        /// <param name="encryptedBytes">The encrypted data to decrypt.</param>
        /// <param name="key">The encryption key.</param>
        /// <returns>The decrypted data.</returns>
        public static byte[] Decrypt(byte[] encryptedBytes, byte[] key)
        {
            using var aes = System.Security.Cryptography.Aes.Create();

            aes.KeySize = KeySizeInBits;
            aes.BlockSize = BlockSizeInBits;

            var (k, iv) = DecodeKey(key);

            using var decryptor = aes.CreateDecryptor(k, iv);
            using var inputStream = new MemoryStream(encryptedBytes);
            using var cryptoStream = new CryptoStream(inputStream, decryptor, CryptoStreamMode.Read);
            using var outputStream = new MemoryStream();

            cryptoStream.CopyTo(outputStream);

            return outputStream.ToArray();
        }

        /// <summary>
        ///     Encrypts the specified <paramref name="plainBytes"/> with the specified <paramref name="key"/>.
        /// </summary>
        /// <param name="plainBytes">The plain data to encrypt.</param>
        /// <param name="key">The encryption key.</param>
        /// <returns>The encrypted data.</returns>
        public static byte[] Encrypt(byte[] plainBytes, byte[] key)
        {
            using var aes = System.Security.Cryptography.Aes.Create();

            aes.KeySize = KeySizeInBits;
            aes.BlockSize = BlockSizeInBits;

            var (k, iv) = DecodeKey(key);

            using var encryptor = aes.CreateEncryptor(k, iv);
            using var outputStream = new MemoryStream();
            using var cryptoStream = new CryptoStream(outputStream, encryptor, CryptoStreamMode.Write);

            cryptoStream.Write(plainBytes, 0, plainBytes.Length);
            cryptoStream.Flush();
            cryptoStream.Close();

            return outputStream.ToArray();
        }

        /// <summary>
        ///     Generates a random key using the default key and block sizes.
        /// </summary>
        /// <returns>The generated key.</returns>
        public static byte[] GenerateRandomKey()
        {
            using var aes = System.Security.Cryptography.Aes.Create();
            aes.KeySize = KeySizeInBits;
            aes.BlockSize = BlockSizeInBits;

            aes.GenerateIV();
            aes.GenerateKey();

            var bytes = aes.Key.Concat(aes.IV).ToArray();
            return bytes;
        }

        private static (byte[] Key, byte[] IV) DecodeKey(byte[] bytes)
        {
            var mem = new Memory<byte>(bytes);
            var key = mem.Slice(0, KeySizeInBytes);
            var iv = mem.Slice(KeySizeInBytes, BlockSizeInBytes);

            return (key.ToArray(), iv.ToArray());
        }
    }
}