summary refs log tree commit diff
path: root/crypto/src/crypto/modes/EAXBlockCipher.cs
blob: bf0d149384fa37e5a1cc52949f573a30e8bdf772 (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
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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
using System;

using Org.BouncyCastle.Crypto.Macs;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Utilities;

namespace Org.BouncyCastle.Crypto.Modes
{
	/**
	* A Two-Pass Authenticated-Encryption Scheme Optimized for Simplicity and 
	* Efficiency - by M. Bellare, P. Rogaway, D. Wagner.
	* 
	* http://www.cs.ucdavis.edu/~rogaway/papers/eax.pdf
	* 
	* EAX is an AEAD scheme based on CTR and OMAC1/CMAC, that uses a single block 
	* cipher to encrypt and authenticate data. It's on-line (the length of a 
	* message isn't needed to begin processing it), has good performances, it's
	* simple and provably secure (provided the underlying block cipher is secure).
	* 
	* Of course, this implementations is NOT thread-safe.
	*/
	public class EaxBlockCipher
		: IAeadBlockCipher
	{
		private enum Tag : byte { N, H, C };

		private SicBlockCipher cipher;

		private bool forEncryption;

		private int blockSize;

		private IMac mac;

		private byte[] nonceMac;
		private byte[] associatedTextMac;
		private byte[] macBlock;

		private int macSize;
		private byte[] bufBlock;
		private int bufOff;

        private bool cipherInitialized;
        private byte[] initialAssociatedText;

		/**
		* Constructor that accepts an instance of a block cipher engine.
		*
		* @param cipher the engine to use
		*/
		public EaxBlockCipher(
			IBlockCipher cipher)
		{
			blockSize = cipher.GetBlockSize();
			mac = new CMac(cipher);
			macBlock = new byte[blockSize];
			associatedTextMac = new byte[mac.GetMacSize()];
			nonceMac = new byte[mac.GetMacSize()];
			this.cipher = new SicBlockCipher(cipher);
		}

		public virtual string AlgorithmName => cipher.UnderlyingCipher.AlgorithmName + "/EAX";

		public virtual IBlockCipher UnderlyingCipher => cipher;

		public virtual int GetBlockSize()
		{
			return cipher.GetBlockSize();
		}

		public virtual void Init(bool forEncryption, ICipherParameters parameters)
		{
			this.forEncryption = forEncryption;

#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
            ReadOnlySpan<byte> nonce;
#else
            byte[] nonce;
#endif
            ICipherParameters keyParam;

			if (parameters is AeadParameters aeadParameters)
			{
#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
                nonce = aeadParameters.Nonce;
#else
                nonce = aeadParameters.GetNonce();
#endif
                initialAssociatedText = aeadParameters.GetAssociatedText();
				macSize = aeadParameters.MacSize / 8;
				keyParam = aeadParameters.Key;
			}
			else if (parameters is ParametersWithIV parametersWithIV)
			{
#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
                nonce = parametersWithIV.IV;
#else
                nonce = parametersWithIV.GetIV();
#endif
                initialAssociatedText = null;
				macSize = mac.GetMacSize() / 2;
				keyParam = parametersWithIV.Parameters;
			}
			else
			{
				throw new ArgumentException("invalid parameters passed to EAX");
			}

            bufBlock = new byte[forEncryption ? blockSize : (blockSize + macSize)];

            byte[] tag = new byte[blockSize];

            // Key reuse implemented in CBC mode of underlying CMac
            mac.Init(keyParam);

            tag[blockSize - 1] = (byte)Tag.N;
            mac.BlockUpdate(tag, 0, blockSize);
#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
            mac.BlockUpdate(nonce);
#else
            mac.BlockUpdate(nonce, 0, nonce.Length);
#endif
            mac.DoFinal(nonceMac, 0);

            // Same BlockCipher underlies this and the mac, so reuse last key on cipher
            cipher.Init(true, new ParametersWithIV(null, nonceMac));

            Reset();
		}

        private void InitCipher()
        {
            if (cipherInitialized)
                return;

            cipherInitialized = true;

            mac.DoFinal(associatedTextMac, 0);

            byte[] tag = new byte[blockSize];
            tag[blockSize - 1] = (byte)Tag.C;
            mac.BlockUpdate(tag, 0, blockSize);
        }

        private void CalculateMac()
		{
			byte[] outC = new byte[blockSize];
			mac.DoFinal(outC, 0);

			for (int i = 0; i < macBlock.Length; i++)
			{
				macBlock[i] = (byte)(nonceMac[i] ^ associatedTextMac[i] ^ outC[i]);
			}
		}

		public virtual void Reset()
		{
			Reset(true);
		}

		private void Reset(
			bool clearMac)
		{
            cipher.Reset(); // TODO Redundant since the mac will reset it?
			mac.Reset();

			bufOff = 0;
			Array.Clear(bufBlock, 0, bufBlock.Length);

			if (clearMac)
			{
				Array.Clear(macBlock, 0, macBlock.Length);
			}

            byte[] tag = new byte[blockSize];
            tag[blockSize - 1] = (byte)Tag.H;
            mac.BlockUpdate(tag, 0, blockSize);

            cipherInitialized = false;

            if (initialAssociatedText != null)
            {
                ProcessAadBytes(initialAssociatedText, 0, initialAssociatedText.Length);
            }
        }
        
        public virtual void ProcessAadByte(byte input)
        {
            if (cipherInitialized)
                throw new InvalidOperationException("AAD data cannot be added after encryption/decryption processing has begun.");

            mac.Update(input);
        }

        public virtual void ProcessAadBytes(byte[] inBytes, int inOff, int len)
        {
            if (cipherInitialized)
                throw new InvalidOperationException("AAD data cannot be added after encryption/decryption processing has begun.");

            mac.BlockUpdate(inBytes, inOff, len);
        }

#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
		public virtual void ProcessAadBytes(ReadOnlySpan<byte> input)
		{
			if (cipherInitialized)
				throw new InvalidOperationException("AAD data cannot be added after encryption/decryption processing has begun.");

			mac.BlockUpdate(input);
		}
#endif

        public virtual int ProcessByte(byte input, byte[] outBytes, int outOff)
		{
            InitCipher();

#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
			return Process(input, Spans.FromNullable(outBytes, outOff));
#else
			return Process(input, outBytes, outOff);
#endif
		}

#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
        public virtual int ProcessByte(byte input, Span<byte> output)
        {
            InitCipher();

            return Process(input, output);
        }
#endif

        public virtual int ProcessBytes(byte[] inBytes, int inOff, int len, byte[] outBytes, int outOff)
        {
#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
			return ProcessBytes(inBytes.AsSpan(inOff, len), Spans.FromNullable(outBytes, outOff));
#else
            InitCipher();

            int resultLen = 0;

			for (int i = 0; i != len; i++)
			{
				resultLen += Process(inBytes[inOff + i], outBytes, outOff + resultLen);
			}

            return resultLen;
#endif
        }

#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
        public virtual int ProcessBytes(ReadOnlySpan<byte> input, Span<byte> output)
        {
            InitCipher();

			int len = input.Length;
            int resultLen = 0;

            for (int i = 0; i != len; i++)
            {
                resultLen += Process(input[i], output[resultLen..]);
            }

            return resultLen;
        }
#endif

        public virtual int DoFinal(byte[] outBytes, int outOff)
		{
#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
			return DoFinal(outBytes.AsSpan(outOff));
#else
			InitCipher();

            int extra = bufOff;
			byte[] tmp = new byte[bufBlock.Length];

            bufOff = 0;

			if (forEncryption)
			{
                Check.OutputLength(outBytes, outOff, extra + macSize, "output buffer too short");

                cipher.ProcessBlock(bufBlock, 0, tmp, 0);

                Array.Copy(tmp, 0, outBytes, outOff, extra);

				mac.BlockUpdate(tmp, 0, extra);

				CalculateMac();

				Array.Copy(macBlock, 0, outBytes, outOff + extra, macSize);

				Reset(false);

				return extra + macSize;
			}
			else
			{
                if (extra < macSize)
                    throw new InvalidCipherTextException("data too short");

                Check.OutputLength(outBytes, outOff, extra - macSize, "output buffer too short");

                if (extra > macSize)
				{
					mac.BlockUpdate(bufBlock, 0, extra - macSize);

					cipher.ProcessBlock(bufBlock, 0, tmp, 0);

                    Array.Copy(tmp, 0, outBytes, outOff, extra - macSize);
				}

				CalculateMac();

				if (!VerifyMac(bufBlock, extra - macSize))
					throw new InvalidCipherTextException("mac check in EAX failed");

				Reset(false);

				return extra - macSize;
			}
#endif
		}

#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
        public virtual int DoFinal(Span<byte> output)
		{
            InitCipher();

            int extra = bufOff;
			int tmpLength = bufBlock.Length;

            Span<byte> tmp = tmpLength <= 128
				? stackalloc byte[tmpLength]
				: new byte[tmpLength];

            bufOff = 0;

			if (forEncryption)
			{
                Check.OutputLength(output, extra + macSize, "output buffer too short");

                cipher.ProcessBlock(bufBlock, tmp);

				tmp[..extra].CopyTo(output);

				mac.BlockUpdate(tmp[..extra]);

				CalculateMac();

				macBlock.AsSpan(0, macSize).CopyTo(output[extra..]);

				Reset(false);

				return extra + macSize;
			}
			else
			{
                if (extra < macSize)
                    throw new InvalidCipherTextException("data too short");

                Check.OutputLength(output, extra - macSize, "output buffer too short");

                if (extra > macSize)
				{
					mac.BlockUpdate(bufBlock.AsSpan(0, extra - macSize));

					cipher.ProcessBlock(bufBlock, tmp);

					tmp[..(extra - macSize)].CopyTo(output);
				}

				CalculateMac();

				if (!VerifyMac(bufBlock, extra - macSize))
					throw new InvalidCipherTextException("mac check in EAX failed");

				Reset(false);

				return extra - macSize;
			}
		}
#endif

        public virtual byte[] GetMac()
		{
			byte[] mac = new byte[macSize];

			Array.Copy(macBlock, 0, mac, 0, macSize);

			return mac;
		}

        public virtual int GetUpdateOutputSize(int len)
		{
            int totalData = len + bufOff;
            if (!forEncryption)
            {
                if (totalData < macSize)
                {
                    return 0;
                }
                totalData -= macSize;
            }
            return totalData - totalData % blockSize;
        }

		public virtual int GetOutputSize(int len)
		{
            int totalData = len + bufOff;

            if (forEncryption)
            {
                return totalData + macSize;
            }

            return totalData < macSize ? 0 : totalData - macSize;
        }

#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
        private int Process(byte b, Span<byte> output)
        {
            bufBlock[bufOff++] = b;

            if (bufOff == bufBlock.Length)
            {
                Check.OutputLength(output, blockSize, "output buffer too short");

                // TODO Could move the ProcessByte(s) calls to here
                //InitCipher();

                int size;

                if (forEncryption)
                {
                    size = cipher.ProcessBlock(bufBlock, output);

					mac.BlockUpdate(output[..blockSize]);
                }
                else
                {
                    mac.BlockUpdate(bufBlock.AsSpan(0, blockSize));

                    size = cipher.ProcessBlock(bufBlock, output);
                }

                bufOff = 0;
                if (!forEncryption)
                {
                    Array.Copy(bufBlock, blockSize, bufBlock, 0, macSize);
                    bufOff = macSize;
                }

                return size;
            }

            return 0;
        }
#else
        private int Process(byte b, byte[] outBytes, int outOff)
        {
            bufBlock[bufOff++] = b;

			if (bufOff == bufBlock.Length)
			{
                Check.OutputLength(outBytes, outOff, blockSize, "output buffer too short");

                // TODO Could move the ProcessByte(s) calls to here
//                InitCipher();

				int size;

				if (forEncryption)
				{
					size = cipher.ProcessBlock(bufBlock, 0, outBytes, outOff);

					mac.BlockUpdate(outBytes, outOff, blockSize);
				}
				else
				{
					mac.BlockUpdate(bufBlock, 0, blockSize);

					size = cipher.ProcessBlock(bufBlock, 0, outBytes, outOff);
				}

                bufOff = 0;
                if (!forEncryption)
                {
                    Array.Copy(bufBlock, blockSize, bufBlock, 0, macSize);
                    bufOff = macSize;
                }

                return size;
			}

			return 0;
		}
#endif

        private bool VerifyMac(byte[] mac, int off)
		{
			return Arrays.FixedTimeEquals(macSize, mac, off, macBlock, 0);
		}
	}
}