summary refs log tree commit diff
path: root/crypto/src/crypto/modes/OCBBlockCipher.cs
blob: 91fdfff181f36962cea17942502d50e61dbfe699 (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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
using System;
using System.Collections;

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

namespace Org.BouncyCastle.Crypto.Modes
{
    /**
     * An implementation of <a href="http://tools.ietf.org/html/rfc7253">RFC 7253 on The OCB
     * Authenticated-Encryption Algorithm</a>, licensed per:
     * 
     * <blockquote><p><a href="http://www.cs.ucdavis.edu/~rogaway/ocb/license1.pdf">License for
     * Open-Source Software Implementations of OCB</a> (Jan 9, 2013) - 'License 1'<br/>
     * Under this license, you are authorized to make, use, and distribute open-source software
     * implementations of OCB. This license terminates for you if you sue someone over their open-source
     * software implementation of OCB claiming that you have a patent covering their implementation.
     * </p><p>
     * This is a non-binding summary of a legal document (the link above). The parameters of the license
     * are specified in the license document and that document is controlling.</p></blockquote>
     */
    public class OcbBlockCipher
        : IAeadBlockCipher
    {
        private const int BLOCK_SIZE = 16;

        private readonly IBlockCipher hashCipher;
        private readonly IBlockCipher mainCipher;

        /*
         * CONFIGURATION
         */
        private bool forEncryption;
        private int macSize;
        private byte[] initialAssociatedText;

        /*
         * KEY-DEPENDENT
         */
        // NOTE: elements are lazily calculated
        private IList L;
        private byte[] L_Asterisk, L_Dollar;

        /*
         * NONCE-DEPENDENT
         */
        private byte[] KtopInput = null;
        private byte[] Stretch = new byte[24];
        private byte[] OffsetMAIN_0 = new byte[16];

        /*
         * PER-ENCRYPTION/DECRYPTION
         */
        private byte[] hashBlock, mainBlock;
        private int hashBlockPos, mainBlockPos;
        private long hashBlockCount, mainBlockCount;
        private byte[] OffsetHASH;
        private byte[] Sum;
        private byte[] OffsetMAIN = new byte[16];
        private byte[] Checksum;

        // NOTE: The MAC value is preserved after doFinal
        private byte[] macBlock;

        public OcbBlockCipher(IBlockCipher hashCipher, IBlockCipher mainCipher)
        {
            if (hashCipher == null)
                throw new ArgumentNullException("hashCipher");
            if (hashCipher.GetBlockSize() != BLOCK_SIZE)
                throw new ArgumentException("must have a block size of " + BLOCK_SIZE, "hashCipher");
            if (mainCipher == null)
                throw new ArgumentNullException("mainCipher");
            if (mainCipher.GetBlockSize() != BLOCK_SIZE)
                throw new ArgumentException("must have a block size of " + BLOCK_SIZE, "mainCipher");

            if (!hashCipher.AlgorithmName.Equals(mainCipher.AlgorithmName))
                throw new ArgumentException("'hashCipher' and 'mainCipher' must be the same algorithm");

            this.hashCipher = hashCipher;
            this.mainCipher = mainCipher;
        }

        public virtual IBlockCipher GetUnderlyingCipher()
        {
            return mainCipher;
        }

        public virtual string AlgorithmName
        {
            get { return mainCipher.AlgorithmName + "/OCB"; }
        }

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

            KeyParameter keyParameter;

            byte[] N;
            if (parameters is AeadParameters)
            {
                AeadParameters aeadParameters = (AeadParameters) parameters;

                N = aeadParameters.GetNonce();
                initialAssociatedText = aeadParameters.GetAssociatedText();

                int macSizeBits = aeadParameters.MacSize;
                if (macSizeBits < 64 || macSizeBits > 128 || macSizeBits % 8 != 0)
                    throw new ArgumentException("Invalid value for MAC size: " + macSizeBits);

                macSize = macSizeBits / 8;
                keyParameter = aeadParameters.Key;
            }
            else if (parameters is ParametersWithIV)
            {
                ParametersWithIV parametersWithIV = (ParametersWithIV) parameters;

                N = parametersWithIV.GetIV();
                initialAssociatedText = null;
                macSize = 16;
                keyParameter = (KeyParameter) parametersWithIV.Parameters;
            }
            else
            {
                throw new ArgumentException("invalid parameters passed to OCB");
            }

            this.hashBlock = new byte[16];
            this.mainBlock = new byte[forEncryption ? BLOCK_SIZE : (BLOCK_SIZE + macSize)];

            if (N == null)
            {
                N = new byte[0];
            }

            if (N.Length > 15)
            {
                throw new ArgumentException("IV must be no more than 15 bytes");
            }

            /*
             * KEY-DEPENDENT INITIALISATION
             */

            if (keyParameter != null)
            {
                // hashCipher always used in forward mode
                hashCipher.Init(true, keyParameter);
                mainCipher.Init(forEncryption, keyParameter);
                KtopInput = null;
            }
            else if (oldForEncryption != forEncryption)
            {
                throw new ArgumentException("cannot change encrypting state without providing key.");
            }

            this.L_Asterisk = new byte[16];
            hashCipher.ProcessBlock(L_Asterisk, 0, L_Asterisk, 0);

            this.L_Dollar = OCB_double(L_Asterisk);

            this.L = Platform.CreateArrayList();
            this.L.Add(OCB_double(L_Dollar));

            /*
             * NONCE-DEPENDENT AND PER-ENCRYPTION/DECRYPTION INITIALISATION
             */

            int bottom = ProcessNonce(N);

            int bits = bottom % 8, bytes = bottom / 8;
            if (bits == 0)
            {
                Array.Copy(Stretch, bytes, OffsetMAIN_0, 0, 16);
            }
            else
            {
                for (int i = 0; i < 16; ++i)
                {
                    uint b1 = Stretch[bytes];
                    uint b2 = Stretch[++bytes];
                    this.OffsetMAIN_0[i] = (byte) ((b1 << bits) | (b2 >> (8 - bits)));
                }
            }

            this.hashBlockPos = 0;
            this.mainBlockPos = 0;

            this.hashBlockCount = 0;
            this.mainBlockCount = 0;

            this.OffsetHASH = new byte[16];
            this.Sum = new byte[16];
            Array.Copy(OffsetMAIN_0, 0, OffsetMAIN, 0, 16);
            this.Checksum = new byte[16];

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

        protected virtual int ProcessNonce(byte[] N)
        {
            byte[] nonce = new byte[16];
            Array.Copy(N, 0, nonce, nonce.Length - N.Length, N.Length);
            nonce[0] = (byte)(macSize << 4);
            nonce[15 - N.Length] |= 1;

            int bottom = nonce[15] & 0x3F;
            nonce[15] &= 0xC0;

            /*
             * When used with incrementing nonces, the cipher is only applied once every 64 inits.
             */
            if (KtopInput == null || !Arrays.AreEqual(nonce, KtopInput))
            {
                byte[] Ktop = new byte[16];
                KtopInput = nonce;
                hashCipher.ProcessBlock(KtopInput, 0, Ktop, 0);
                Array.Copy(Ktop, 0, Stretch, 0, 16);
                for (int i = 0; i < 8; ++i)
                {
                    Stretch[16 + i] = (byte)(Ktop[i] ^ Ktop[i + 1]);
                }
            }

            return bottom;
        }

        public virtual int GetBlockSize()
        {
            return BLOCK_SIZE;
        }

        public virtual byte[] GetMac()
        {
            return macBlock == null
                ? new byte[macSize]
                : Arrays.Clone(macBlock);
        }

        public virtual int GetOutputSize(int len)
        {
            int totalData = len + mainBlockPos;
            if (forEncryption)
            {
                return totalData + macSize;
            }
            return totalData < macSize ? 0 : totalData - macSize;
        }

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

        public virtual void ProcessAadByte(byte input)
        {
            hashBlock[hashBlockPos] = input;
            if (++hashBlockPos == hashBlock.Length)
            {
                ProcessHashBlock();
            }
        }

        public virtual void ProcessAadBytes(byte[] input, int off, int len)
        {
            for (int i = 0; i < len; ++i)
            {
                hashBlock[hashBlockPos] = input[off + i];
                if (++hashBlockPos == hashBlock.Length)
                {
                    ProcessHashBlock();
                }
            }
        }

        public virtual int ProcessByte(byte input, byte[] output, int outOff)
        {
            mainBlock[mainBlockPos] = input;
            if (++mainBlockPos == mainBlock.Length)
            {
                ProcessMainBlock(output, outOff);
                return BLOCK_SIZE;
            }
            return 0;
        }

        public virtual int ProcessBytes(byte[] input, int inOff, int len, byte[] output, int outOff)
        {
            int resultLen = 0;

            for (int i = 0; i < len; ++i)
            {
                mainBlock[mainBlockPos] = input[inOff + i];
                if (++mainBlockPos == mainBlock.Length)
                {
                    ProcessMainBlock(output, outOff + resultLen);
                    resultLen += BLOCK_SIZE;
                }
            }

            return resultLen;
        }

        public virtual int DoFinal(byte[] output, int outOff)
        {
            /*
             * For decryption, get the tag from the end of the message
             */
            byte[] tag = null;
            if (!forEncryption) {
                if (mainBlockPos < macSize)
                    throw new InvalidCipherTextException("data too short");

                mainBlockPos -= macSize;
                tag = new byte[macSize];
                Array.Copy(mainBlock, mainBlockPos, tag, 0, macSize);
            }

            /*
             * HASH: Process any final partial block; compute final hash value
             */
            if (hashBlockPos > 0)
            {
                OCB_extend(hashBlock, hashBlockPos);
                UpdateHASH(L_Asterisk);
            }

            /*
             * OCB-ENCRYPT/OCB-DECRYPT: Process any final partial block
             */
            if (mainBlockPos > 0)
            {
                if (forEncryption)
                {
                    OCB_extend(mainBlock, mainBlockPos);
                    Xor(Checksum, mainBlock);
                }

                Xor(OffsetMAIN, L_Asterisk);

                byte[] Pad = new byte[16];
                hashCipher.ProcessBlock(OffsetMAIN, 0, Pad, 0);

                Xor(mainBlock, Pad);

                Check.OutputLength(output, outOff, mainBlockPos, "Output buffer too short");
                Array.Copy(mainBlock, 0, output, outOff, mainBlockPos);

                if (!forEncryption)
                {
                    OCB_extend(mainBlock, mainBlockPos);
                    Xor(Checksum, mainBlock);
                }
            }

            /*
             * OCB-ENCRYPT/OCB-DECRYPT: Compute raw tag
             */
            Xor(Checksum, OffsetMAIN);
            Xor(Checksum, L_Dollar);
            hashCipher.ProcessBlock(Checksum, 0, Checksum, 0);
            Xor(Checksum, Sum);

            this.macBlock = new byte[macSize];
            Array.Copy(Checksum, 0, macBlock, 0, macSize);

            /*
             * Validate or append tag and reset this cipher for the next run
             */
            int resultLen = mainBlockPos;

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

                // Append tag to the message
                Array.Copy(macBlock, 0, output, outOff + resultLen, macSize);
                resultLen += macSize;
            }
            else
            {
                // Compare the tag from the message with the calculated one
                if (!Arrays.ConstantTimeAreEqual(macBlock, tag))
                    throw new InvalidCipherTextException("mac check in OCB failed");
            }

            Reset(false);

            return resultLen;
        }

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

        protected virtual void Clear(byte[] bs)
        {
            if (bs != null)
            {
                Array.Clear(bs, 0, bs.Length);
            }
        }

        protected virtual byte[] GetLSub(int n)
        {
            while (n >= L.Count)
            {
                L.Add(OCB_double((byte[]) L[L.Count - 1]));
            }
            return (byte[])L[n];
        }

        protected virtual void ProcessHashBlock()
        {
            /*
             * HASH: Process any whole blocks
             */
            UpdateHASH(GetLSub(OCB_ntz(++hashBlockCount)));
            hashBlockPos = 0;
        }

        protected virtual void ProcessMainBlock(byte[] output, int outOff)
        {
            Check.DataLength(output, outOff, BLOCK_SIZE, "Output buffer too short");

            /*
             * OCB-ENCRYPT/OCB-DECRYPT: Process any whole blocks
             */

            if (forEncryption)
            {
                Xor(Checksum, mainBlock);
                mainBlockPos = 0;
            }

            Xor(OffsetMAIN, GetLSub(OCB_ntz(++mainBlockCount)));

            Xor(mainBlock, OffsetMAIN);
            mainCipher.ProcessBlock(mainBlock, 0, mainBlock, 0);
            Xor(mainBlock, OffsetMAIN);

            Array.Copy(mainBlock, 0, output, outOff, 16);

            if (!forEncryption)
            {
                Xor(Checksum, mainBlock);
                Array.Copy(mainBlock, BLOCK_SIZE, mainBlock, 0, macSize);
                mainBlockPos = macSize;
            }
        }

        protected virtual void Reset(bool clearMac)
        {
            hashCipher.Reset();
            mainCipher.Reset();

            Clear(hashBlock);
            Clear(mainBlock);

            hashBlockPos = 0;
            mainBlockPos = 0;

            hashBlockCount = 0;
            mainBlockCount = 0;

            Clear(OffsetHASH);
            Clear(Sum);
            Array.Copy(OffsetMAIN_0, 0, OffsetMAIN, 0, 16);
            Clear(Checksum);

            if (clearMac)
            {
                macBlock = null;
            }

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

        protected virtual void UpdateHASH(byte[] LSub)
        {
            Xor(OffsetHASH, LSub);
            Xor(hashBlock, OffsetHASH);
            hashCipher.ProcessBlock(hashBlock, 0, hashBlock, 0);
            Xor(Sum, hashBlock);
        }

        protected static byte[] OCB_double(byte[] block)
        {
            byte[] result = new byte[16];
            int carry = ShiftLeft(block, result);

            /*
             * NOTE: This construction is an attempt at a constant-time implementation.
             */
            result[15] ^= (byte)(0x87 >> ((1 - carry) << 3));

            return result;
        }

        protected static void OCB_extend(byte[] block, int pos)
        {
            block[pos] = (byte) 0x80;
            while (++pos < 16)
            {
                block[pos] = 0;
            }
        }

        protected static int OCB_ntz(long x)
        {
            if (x == 0)
            {
                return 64;
            }

            int n = 0;
            ulong ux = (ulong)x;
            while ((ux & 1UL) == 0UL)
            {
                ++n;
                ux >>= 1;
            }
            return n;
        }

        protected static int ShiftLeft(byte[] block, byte[] output)
        {
            int i = 16;
            uint bit = 0;
            while (--i >= 0)
            {
                uint b = block[i];
                output[i] = (byte) ((b << 1) | bit);
                bit = (b >> 7) & 1;
            }
            return (int)bit;
        }

        protected static void Xor(byte[] block, byte[] val)
        {
            for (int i = 15; i >= 0; --i)
            {
                block[i] ^= val[i];
            }
        }
    }
}