-
Notifications
You must be signed in to change notification settings - Fork 0
/
AesCtr.cs
170 lines (143 loc) · 5.62 KB
/
AesCtr.cs
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
namespace Noita_UnlockAllProgress
{
public class AesCounterMode : SymmetricAlgorithm
{
private readonly ulong _nonce;
private readonly ulong _counter;
private readonly AesManaged _aes;
public AesCounterMode(byte[] nonce, ulong counter)
: this(ConvertNonce(nonce), counter)
{
}
public AesCounterMode(ulong nonce, ulong counter)
{
_aes = new AesManaged
{
Mode = CipherMode.ECB,
Padding = PaddingMode.None
};
_nonce = nonce;
_counter = counter;
}
private static ulong ConvertNonce(byte[] nonce)
{
if (nonce == null) throw new ArgumentNullException(nameof(nonce));
if (nonce.Length < sizeof(ulong)) throw new ArgumentException($"{nameof(nonce)} must have at least {sizeof(ulong)} bytes");
return BitConverter.ToUInt64(nonce);
}
public override ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[] ignoredParameter)
{
return new CounterModeCryptoTransform(_aes, rgbKey, _nonce, _counter);
}
public override ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[] ignoredParameter)
{
return new CounterModeCryptoTransform(_aes, rgbKey, _nonce, _counter);
}
public override void GenerateKey()
{
_aes.GenerateKey();
}
public override void GenerateIV()
{
// IV not needed in Counter Mode
}
}
public class CounterModeCryptoTransform : ICryptoTransform
{
private readonly byte[] _nonceAndCounter;
private readonly ICryptoTransform _counterEncryptor;
private readonly Queue<byte> _xorMask = new Queue<byte>();
private readonly SymmetricAlgorithm _symmetricAlgorithm;
private ulong _counter;
public CounterModeCryptoTransform(SymmetricAlgorithm symmetricAlgorithm, byte[] key, ulong nonce, ulong counter)
{
if (key == null) throw new ArgumentNullException(nameof(key));
_symmetricAlgorithm = symmetricAlgorithm ?? throw new ArgumentNullException(nameof(symmetricAlgorithm));
_counter = counter;
_nonceAndCounter = new byte[16];
BitConverter.TryWriteBytes(_nonceAndCounter, nonce);
BitConverter.TryWriteBytes(new Span<byte>(_nonceAndCounter, sizeof(ulong), sizeof(ulong)), counter);
var zeroIv = new byte[_symmetricAlgorithm.BlockSize / 8];
_counterEncryptor = symmetricAlgorithm.CreateEncryptor(key, zeroIv);
}
public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount)
{
var output = new byte[inputCount];
TransformBlock(inputBuffer, inputOffset, inputCount, output, 0);
return output;
}
public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer,
int outputOffset)
{
for (var i = 0; i < inputCount; i++)
{
if (NeedMoreXorMaskBytes())
{
EncryptCounterThenIncrement();
}
var mask = _xorMask.Dequeue();
outputBuffer[outputOffset + i] = (byte)(inputBuffer[inputOffset + i] ^ mask);
}
return inputCount;
}
private bool NeedMoreXorMaskBytes()
{
return _xorMask.Count == 0;
}
private byte[] _counterModeBlock;
private void EncryptCounterThenIncrement()
{
_counterModeBlock ??= new byte[_symmetricAlgorithm.BlockSize / 8];
_counterEncryptor.TransformBlock(_nonceAndCounter, 0, _nonceAndCounter.Length, _counterModeBlock, 0);
IncrementCounter();
foreach (var b in _counterModeBlock)
{
_xorMask.Enqueue(b);
}
}
private void IncrementCounter()
{
_counter++;
var span = new Span<byte>(_nonceAndCounter, sizeof(ulong), sizeof(ulong));
BitConverter.TryWriteBytes(span, _counter);
}
public int InputBlockSize => _symmetricAlgorithm.BlockSize / 8;
public int OutputBlockSize => _symmetricAlgorithm.BlockSize / 8;
public bool CanTransformMultipleBlocks => true;
public bool CanReuseTransform => false;
public void Dispose()
{
_counterEncryptor.Dispose();
}
}
//public void ExampleUsage()
//{
// var key = new byte[16];
// RandomNumberGenerator.Create().GetBytes(key);
// var nonce = new byte[8];
// RandomNumberGenerator.Create().GetBytes(nonce);
//
// var dataToEncrypt = new byte[12345];
//
// var counter = 0;
// using var counterMode = new AesCounterMode(nonce, counter);
// using var encryptor = counterMode.CreateEncryptor(key, null);
// using var decryptor = counterMode.CreateDecryptor(key, null);
//
// var encryptedData = new byte[dataToEncrypt.Length];
// var bytesWritten = encryptor.TransformBlock(dataToEncrypt, 0, dataToEncrypt.Length, encryptedData, 0);
//
// var decrypted = new byte[dataToEncrypt.Length];
// decryptor.TransformBlock(encryptedData, 0, bytesWritten, decrypted, 0);
//
// //decrypted.Should().BeEquivalentTo(dataToEncrypt);
//}
}