summary refs log tree commit diff
path: root/crypto/src/crypto/fpe/SP80038G.cs
blob: a9dc7f144fe730967bf2f3a55172f4df8a5f33c4 (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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
using System;

using Org.BouncyCastle.Crypto.Utilities;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Utilities;

namespace Org.BouncyCastle.Crypto.Fpe
{
    /*
	 * SP800-38G Format-Preserving Encryption
	 *
	 * TODOs
	 * - Initialize the cipher internally or externally?
	 *     1. Algs 7-10 don't appear to require forward vs. inverse transform, although sample data is forward.
	 *     2. Algs 9-10 specify reversal of the cipher key!
	 * - Separate construction/initialization stage for "prerequisites"
	 */
    internal class SP80038G
    {
        internal static readonly string FPE_DISABLED = "Org.BouncyCastle.Fpe.Disable";
        internal static readonly string FF1_DISABLED = "Org.BouncyCastle.Fpe.Disable_Ff1";

        protected static readonly int BLOCK_SIZE = 16;
        protected static readonly double LOG2 = System.Math.Log(2.0);
        protected static readonly double TWO_TO_96 = System.Math.Pow(2, 96);

        public static byte[] DecryptFF1(IBlockCipher cipher, int radix, byte[] tweak, byte[] buf, int off, int len)
        {
            checkArgs(cipher, true, radix, buf, off, len);

            // Algorithm 8
            int n = len;
            int u = n / 2, v = n - u;

            ushort[] A = toShort(buf, off, u);
            ushort[] B = toShort(buf, off + u, v);

            ushort[] rv = decFF1(cipher, radix, tweak, n, u, v, A, B);

            return toByte(rv);
        }

        public static ushort[] DecryptFF1w(IBlockCipher cipher, int radix, byte[] tweak, ushort[] buf, int off, int len)
        {
            checkArgs(cipher, true, radix, buf, off, len);

            // Algorithm 8
            int n = len;
            int u = n / 2, v = n - u;

            ushort[] A = new ushort[u];
            ushort[] B = new ushort[v];

            Array.Copy(buf, off, A, 0, u);
            Array.Copy(buf, off + u, B, 0, v);

            return decFF1(cipher, radix, tweak, n, u, v, A, B);
        }

        private static ushort[] decFF1(IBlockCipher cipher, int radix, byte[] T, int n, int u, int v, ushort[] A, ushort[] B)
        {
            int t = T.Length;
            int b = ((int)Ceil(System.Math.Log((double)radix) * (double)v / LOG2) + 7) / 8;
            int d = (((b + 3) / 4) * 4) + 4;

            byte[] P = calculateP_FF1(radix, (byte)u, n, t);

            BigInteger bigRadix = BigInteger.ValueOf(radix);
            BigInteger[] modUV = calculateModUV(bigRadix, u, v);

            int m = u;

            for (int i = 9; i >= 0; --i)
            {
                // i. - iv.
                BigInteger y = calculateY_FF1(cipher, bigRadix, T, b, d, i, P, A);

                // v.
                m = n - m;
                BigInteger modulus = modUV[i & 1];

                // vi.
                BigInteger c = num(bigRadix, B).Subtract(y).Mod(modulus);

                // vii. - ix.
                ushort[] C = B;
                B = A;
                A = C;
                str(bigRadix, c, m, C, 0);
            }

            return Arrays.Concatenate(A, B);
        }

        public static byte[] DecryptFF3(IBlockCipher cipher, int radix, byte[] tweak64, byte[] buf, int off, int len)
        {
            checkArgs(cipher, false, radix, buf, off, len);

            if (tweak64.Length != 8)
            {
                throw new ArgumentException();
            }

            return implDecryptFF3(cipher, radix, tweak64, buf, off, len);
        }

        public static byte[] DecryptFF3_1(IBlockCipher cipher, int radix, byte[] tweak56, byte[] buf, int off, int len)
        {
            checkArgs(cipher, false, radix, buf, off, len);

            if (tweak56.Length != 7)
            {
                throw new ArgumentException("tweak should be 56 bits");
            }

            byte[] tweak64 = calculateTweak64_FF3_1(tweak56);

            return implDecryptFF3(cipher, radix, tweak64, buf, off, len);
        }

        public static ushort[] DecryptFF3_1w(IBlockCipher cipher, int radix, byte[] tweak56, ushort[] buf, int off, int len)
        {
            checkArgs(cipher, false, radix, buf, off, len);

            if (tweak56.Length != 7)
            {
                throw new ArgumentException("tweak should be 56 bits");
            }

            byte[] tweak64 = calculateTweak64_FF3_1(tweak56);

            return implDecryptFF3w(cipher, radix, tweak64, buf, off, len);
        }

        public static byte[] EncryptFF1(IBlockCipher cipher, int radix, byte[] tweak, byte[] buf, int off, int len)
        {
            checkArgs(cipher, true, radix, buf, off, len);

            // Algorithm 7
            int n = len;
            int u = n / 2, v = n - u;

            ushort[] A = toShort(buf, off, u);
            ushort[] B = toShort(buf, off + u, v);

            return toByte(encFF1(cipher, radix, tweak, n, u, v, A, B));
        }

        public static ushort[] EncryptFF1w(IBlockCipher cipher, int radix, byte[] tweak, ushort[] buf, int off, int len)
        {
            checkArgs(cipher, true, radix, buf, off, len);

            // Algorithm 7
            int n = len;
            int u = n / 2, v = n - u;

            ushort[] A = new ushort[u];
            ushort[] B = new ushort[v];

            Array.Copy(buf, off, A, 0, u);
            Array.Copy(buf, off + u, B, 0, v);

            return encFF1(cipher, radix, tweak, n, u, v, A, B);
        }

        private static ushort[] encFF1(IBlockCipher cipher, int radix, byte[] T, int n, int u, int v, ushort[] A, ushort[] B)
        {
            int t = T.Length;

            int b = ((int)Ceil(System.Math.Log((double)radix) * (double)v / LOG2) + 7) / 8;
            int d = (((b + 3) / 4) * 4) + 4;

            byte[] P = calculateP_FF1(radix, (byte)u, n, t);

            BigInteger bigRadix = BigInteger.ValueOf(radix);
            BigInteger[] modUV = calculateModUV(bigRadix, u, v);

            int m = v;

            for (int i = 0; i < 10; ++i)
            {
                // i. - iv.
                BigInteger y = calculateY_FF1(cipher, bigRadix, T, b, d, i, P, B);

                // v.
                m = n - m;
                BigInteger modulus = modUV[i & 1];

                // vi.
                BigInteger c = num(bigRadix, A).Add(y).Mod(modulus);

                // vii. - ix.
                ushort[] C = A;
                A = B;
                B = C;
                str(bigRadix, c, m, C, 0);
            }

            return Arrays.Concatenate(A, B);
        }

        public static byte[] EncryptFF3(IBlockCipher cipher, int radix, byte[] tweak64, byte[] buf, int off, int len)
        {
            checkArgs(cipher, false, radix, buf, off, len);

            if (tweak64.Length != 8)
            {
                throw new ArgumentException();
            }

            return implEncryptFF3(cipher, radix, tweak64, buf, off, len);
        }

        public static ushort[] EncryptFF3w(IBlockCipher cipher, int radix, byte[] tweak64, ushort[] buf, int off, int len)
        {
            checkArgs(cipher, false, radix, buf, off, len);

            if (tweak64.Length != 8)
            {
                throw new ArgumentException();
            }

            return implEncryptFF3w(cipher, radix, tweak64, buf, off, len);
        }

        public static ushort[] EncryptFF3_1w(IBlockCipher cipher, int radix, byte[] tweak56, ushort[] buf, int off, int len)
        {
            checkArgs(cipher, false, radix, buf, off, len);

            if (tweak56.Length != 7)
            {
                throw new ArgumentException("tweak should be 56 bits");
            }
            byte[] tweak64 = calculateTweak64_FF3_1(tweak56);

            return EncryptFF3w(cipher, radix, tweak64, buf, off, len);
        }

        public static byte[] EncryptFF3_1(IBlockCipher cipher, int radix, byte[] tweak56, byte[] buf, int off, int len)
        {
            checkArgs(cipher, false, radix, buf, off, len);

            if (tweak56.Length != 7)
            {
                throw new ArgumentException("tweak should be 56 bits");
            }

            byte[] tweak64 = calculateTweak64_FF3_1(tweak56);

            return EncryptFF3(cipher, radix, tweak64, buf, off, len);
        }

        protected static BigInteger[] calculateModUV(BigInteger bigRadix, int u, int v)
        {
            BigInteger[] modUV = new BigInteger[2];
            modUV[0] = bigRadix.Pow(u);
            modUV[1] = modUV[0];
            if (v != u)
            {
                modUV[1] = modUV[1].Multiply(bigRadix);
            }
            return modUV;
        }

        protected static byte[] calculateP_FF1(int radix, byte uLow, int n, int t)
        {
            byte[] P = new byte[BLOCK_SIZE];
            P[0] = 1;
            P[1] = 2;
            P[2] = 1;

            // Radix
            P[3] = 0;
            P[4] = (byte)(radix >> 8);
            P[5] = (byte)radix;

            P[6] = 10;
            P[7] = uLow;
            Pack.UInt32_To_BE((uint)n, P, 8);
            Pack.UInt32_To_BE((uint)t, P, 12);
            return P;
        }

        protected static byte[] calculateTweak64_FF3_1(byte[] tweak56)
        {
            byte[] tweak64 = new byte[8];
            tweak64[0] = tweak56[0];
            tweak64[1] = tweak56[1];
            tweak64[2] = tweak56[2];
            tweak64[3] = (byte)(tweak56[3] & 0xF0);
            tweak64[4] = tweak56[4];
            tweak64[5] = tweak56[5];
            tweak64[6] = tweak56[6];
            tweak64[7] = (byte)(tweak56[3] << 4);

            return tweak64;
        }

        protected static BigInteger calculateY_FF1(IBlockCipher cipher, BigInteger bigRadix, byte[] T, int b, int d, int round, byte[] P, ushort[] AB)
        {
            int t = T.Length;

            // i.
            int zeroes = -(t + b + 1) & 15;
            byte[] Q = new byte[t + zeroes + 1 + b];
            Array.Copy(T, 0, Q, 0, t);
            Q[t + zeroes] = (byte)round;

            BigInteger numAB = num(bigRadix, AB);
            BigIntegers.AsUnsignedByteArray(numAB, Q, Q.Length - b, b);

            // ii.
            byte[] R = prf(cipher, Arrays.Concatenate(P, Q));

            // iii.
            byte[] sBlocks = R;
            if (d > BLOCK_SIZE)
            {
                int sBlocksLen = (d + BLOCK_SIZE - 1) / BLOCK_SIZE;
                sBlocks = new byte[sBlocksLen * BLOCK_SIZE];

                uint j0 = Pack.BE_To_UInt32(R, BLOCK_SIZE - 4);
                Array.Copy(R, 0, sBlocks, 0, BLOCK_SIZE);

                for (uint j = 1; j < sBlocksLen; ++j)
                {
                    int sOff = (int)(j * BLOCK_SIZE);

                    Array.Copy(R, 0, sBlocks, sOff, BLOCK_SIZE - 4);
                    Pack.UInt32_To_BE(j0 ^ j, sBlocks, sOff + BLOCK_SIZE - 4);

                    cipher.ProcessBlock(sBlocks, sOff, sBlocks, sOff);
                }
            }

            // iv.
            return new BigInteger(1, sBlocks, 0, d);
        }

        protected static BigInteger calculateY_FF3(IBlockCipher cipher, BigInteger bigRadix, byte[] T, int wOff,
            uint round, ushort[] AB)
        {
            // ii.
            byte[] P = new byte[BLOCK_SIZE];
            Pack.UInt32_To_BE(Pack.BE_To_UInt32(T, wOff) ^ round, P, 0);

            BigInteger numAB = num(bigRadix, AB);
            BigIntegers.AsUnsignedByteArray(numAB, P, 4, BLOCK_SIZE - 4);

            // iii.
            Array.Reverse(P);
            cipher.ProcessBlock(P, 0, P, 0);
            Array.Reverse(P);
            byte[] S = P;

            // iv.
            return new BigInteger(1, S);
        }

        protected static void checkArgs(IBlockCipher cipher, bool isFF1, int radix, ushort[] buf, int off, int len)
        {
            checkCipher(cipher);
            if (radix < 2 || radix > (1 << 16))
            {
                throw new ArgumentException();
            }
            checkData(isFF1, radix, buf, off, len);
        }

        protected static void checkArgs(IBlockCipher cipher, bool isFF1, int radix, byte[] buf, int off, int len)
        {
            checkCipher(cipher);
            if (radix < 2 || radix > (1 << 8))
            {
                throw new ArgumentException();
            }
            checkData(isFF1, radix, buf, off, len);
        }

        protected static void checkCipher(IBlockCipher cipher)
        {
            if (BLOCK_SIZE != cipher.GetBlockSize())
            {
                throw new ArgumentException();
            }
        }

        protected static void checkData(bool isFF1, int radix, ushort[] buf, int off, int len)
        {
            checkLength(isFF1, radix, len);
            for (int i = 0; i < len; ++i)
            {
                int b = buf[off + i] & 0xFFFF;
                if (b >= radix)
                {
                    throw new ArgumentException("input data outside of radix");
                }
            }
        }

        protected static void checkData(bool isFF1, int radix, byte[] buf, int off, int len)
        {
            checkLength(isFF1, radix, len);
            for (int i = 0; i < len; ++i)
            {
                int b = buf[off + i] & 0xFF;
                if (b >= radix)
                {
                    throw new ArgumentException("input data outside of radix");
                }
            }
        }

        private static void checkLength(bool isFF1, int radix, int len)
        {
            if (len < 2 || System.Math.Pow(radix, len) < 1000000)
            {
                throw new ArgumentException("input too short");
            }
            if (!isFF1)
            {
                int maxLen = 2 * (int)(System.Math.Floor(System.Math.Log(TWO_TO_96) / System.Math.Log(radix)));
                if (len > maxLen)
                {
                    throw new ArgumentException("maximum input length is " + maxLen);
                }
            }
        }

        protected static byte[] implDecryptFF3(IBlockCipher cipher, int radix, byte[] tweak64, byte[] buf, int off, int len)
        {
            // Algorithm 10
            byte[] T = tweak64;
            int n = len;
            int v = n / 2, u = n - v;

            ushort[] A = toShort(buf, off, u);
            ushort[] B = toShort(buf, off + u, v);

            ushort[] rv = decFF3_1(cipher, radix, T, n, v, u, A, B);

            return toByte(rv);
        }

        protected static ushort[] implDecryptFF3w(IBlockCipher cipher, int radix, byte[] tweak64, ushort[] buf, int off, int len)
        {
            // Algorithm 10
            byte[] T = tweak64;
            int n = len;
            int v = n / 2, u = n - v;

            ushort[] A = new ushort[u];
            ushort[] B = new ushort[v];

            Array.Copy(buf, off, A, 0, u);
            Array.Copy(buf, off + u, B, 0, v);

            return decFF3_1(cipher, radix, T, n, v, u, A, B);
        }

        private static ushort[] decFF3_1(IBlockCipher cipher, int radix, byte[] T, int n, int v, int u, ushort[] A, ushort[] B)
        {
            BigInteger bigRadix = BigInteger.ValueOf(radix);
            BigInteger[] modVU = calculateModUV(bigRadix, v, u);

            int m = u;

            // Note we keep A, B in reverse order throughout
            Array.Reverse(A);
            Array.Reverse(B);

            for (int i = 7; i >= 0; --i)
            {
                // i.
                m = n - m;
                BigInteger modulus = modVU[1 - (i & 1)];
                int wOff = 4 - ((i & 1) * 4);

                // ii. - iv.
                BigInteger y = calculateY_FF3(cipher, bigRadix, T, wOff, (uint)i, A);

                // v.
                BigInteger c = num(bigRadix, B).Subtract(y).Mod(modulus);

                // vi. - viii.
                ushort[] C = B;
                B = A;
                A = C;
                str(bigRadix, c, m, C, 0);
            }

            Array.Reverse(A);
            Array.Reverse(B);

            return Arrays.Concatenate(A, B);
        }

        protected static byte[] implEncryptFF3(IBlockCipher cipher, int radix, byte[] tweak64, byte[] buf, int off, int len)
        {
            // Algorithm 9
            byte[] T = tweak64;
            int n = len;
            int v = n / 2, u = n - v;

            ushort[] A = toShort(buf, off, u);
            ushort[] B = toShort(buf, off + u, v);

            ushort[] rv = encFF3_1(cipher, radix, T, n, v, u, A, B);

            return toByte(rv);
        }

        protected static ushort[] implEncryptFF3w(IBlockCipher cipher, int radix, byte[] tweak64, ushort[] buf, int off, int len)
        {
            // Algorithm 9
            byte[] T = tweak64;
            int n = len;
            int v = n / 2, u = n - v;

            ushort[] A = new ushort[u];
            ushort[] B = new ushort[v];

            Array.Copy(buf, off, A, 0, u);
            Array.Copy(buf, off + u, B, 0, v);

            return encFF3_1(cipher, radix, T, n, v, u, A, B);
        }

        private static ushort[] encFF3_1(IBlockCipher cipher, int radix, byte[] t, int n, int v, int u, ushort[] a, ushort[] b)
        {
            BigInteger bigRadix = BigInteger.ValueOf(radix);
            BigInteger[] modVU = calculateModUV(bigRadix, v, u);

            int m = v;

            // Note we keep A, B in reverse order throughout
            Array.Reverse(a);
            Array.Reverse(b);

            for (uint i = 0; i < 8; ++i)
            {
                // i.
                m = n - m;
                BigInteger modulus = modVU[1 - (i & 1)];
                int wOff = 4 - (int)((i & 1) * 4);

                // ii. - iv.
                BigInteger y = calculateY_FF3(cipher, bigRadix, t, wOff, i, b);

                // v.
                BigInteger c = num(bigRadix, a).Add(y).Mod(modulus);

                // vi. - viii.
                ushort[] C = a;
                a = b;
                b = C;
                str(bigRadix, c, m, C, 0);
            }

            Array.Reverse(a);
            Array.Reverse(b);

            return Arrays.Concatenate(a, b);
        }

        protected static BigInteger num(BigInteger R, ushort[] x)
        {
            BigInteger result = BigInteger.Zero;
            for (int i = 0; i < x.Length; ++i)
            {
                result = result.Multiply(R).Add(BigInteger.ValueOf(x[i] & 0xFFFF));
            }
            return result;
        }

        protected static byte[] prf(IBlockCipher c, byte[] x)
        {
            if ((x.Length % BLOCK_SIZE) != 0)
                throw new ArgumentException();

            int m = x.Length / BLOCK_SIZE;
            byte[] y = new byte[BLOCK_SIZE];

            for (int i = 0; i < m; ++i)
            {
                xor(x, i * BLOCK_SIZE, y, 0, BLOCK_SIZE);
                c.ProcessBlock(y, 0, y, 0);
            }

            return y;
        }

        protected static void str(BigInteger R, BigInteger x, int m, ushort[] output, int off)
        {
            if (x.SignValue < 0)
                throw new ArgumentException();

            for (int i = 1; i <= m; ++i)
            {
                BigInteger[] qr = x.DivideAndRemainder(R);
                output[off + m - i] = (ushort)qr[1].IntValue;
                x = qr[0];
            }
            if (x.SignValue != 0)
                throw new ArgumentException();
        }

        protected static void xor(byte[] x, int xOff, byte[] y, int yOff, int len)
        {
            for (int i = 0; i < len; ++i)
            {
                y[yOff + i] ^= x[xOff + i];
            }
        }

        private static byte[] toByte(ushort[] buf)
        {
            byte[] s = new byte[buf.Length];

            for (int i = 0; i != s.Length; i++)
            {
                s[i] = (byte)buf[i];
            }

            return s;
        }

        private static ushort[] toShort(byte[] buf, int off, int len)
        {
            ushort[] s = new ushort[len];

            for (int i = 0; i != s.Length; i++)
            {
                s[i] = (ushort)(buf[off + i] & 0xFF);
            }

            return s;
        }

	    private static int Ceil(double v)
	    {
		    int rv = (int)v;
		    if ((double)rv < v)
			    return rv + 1;

            return rv;
	    }
    }
}