summary refs log tree commit diff
path: root/crypto/src/crypto/modes/EAXBlockCipher.cs
blob: bb027b597f31484b6e8d2a696b2789bec27d479d (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
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];
			bufBlock = new byte[blockSize * 2];
			associatedTextMac = new byte[mac.GetMacSize()];
			nonceMac = new byte[mac.GetMacSize()];
			this.cipher = new SicBlockCipher(cipher);
		}

		public virtual string AlgorithmName
		{
			get { return cipher.GetUnderlyingCipher().AlgorithmName + "/EAX"; }
		}

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

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

			byte[] nonce;
			ICipherParameters keyParam;

			if (parameters is AeadParameters)
			{
				AeadParameters param = (AeadParameters) parameters;

				nonce = param.GetNonce();
                initialAssociatedText = param.GetAssociatedText();
				macSize = param.MacSize / 8;
				keyParam = param.Key;
			}
			else if (parameters is ParametersWithIV)
			{
				ParametersWithIV param = (ParametersWithIV) parameters;

				nonce = param.GetIV();
                initialAssociatedText = null;
				macSize = mac.GetMacSize() / 2;
				keyParam = param.Parameters;
			}
			else
			{
				throw new ArgumentException("invalid parameters passed to EAX");
			}

            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);
            mac.BlockUpdate(nonce, 0, nonce.Length);
            mac.DoFinal(nonceMac, 0);

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

            if (initialAssociatedText != null)
            {
                ProcessAadBytes(initialAssociatedText, 0, initialAssociatedText.Length);
            }

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

        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/decription processing has begun.");
            }
            mac.Update(input);
        }

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

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

            return Process(input, outBytes, outOff);
		}

        public virtual int ProcessBytes(
			byte[]	inBytes,
			int		inOff,
			int		len,
			byte[]	outBytes,
			int		outOff)
		{
            InitCipher();

            int resultLen = 0;

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

            return resultLen;
		}

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

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

            bufOff = 0;

			if (forEncryption)
			{
				cipher.ProcessBlock(bufBlock, 0, tmp, 0);
				cipher.ProcessBlock(bufBlock, blockSize, tmp, blockSize);

				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)
				{
					mac.BlockUpdate(bufBlock, 0, extra - macSize);

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

					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;
			}
		}

		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;
        }

		private int Process(
			byte	b,
			byte[]	outBytes,
			int		outOff)
		{
			bufBlock[bufOff++] = b;

			if (bufOff == bufBlock.Length)
			{
				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 = blockSize;
				Array.Copy(bufBlock, blockSize, bufBlock, 0, blockSize);

				return size;
			}

			return 0;
		}

		private bool VerifyMac(byte[] mac, int off)
		{
            int nonEqual = 0;

            for (int i = 0; i < macSize; i++)
            {
                nonEqual |= (macBlock[i] ^ mac[off + i]);
            }

            return nonEqual == 0;
		}
	}
}