summary refs log tree commit diff
path: root/crypto/src/crypto/engines/AsconEngine.cs
blob: 14d3ddf6d7337f174b416c5c2ccf06c821acdad3 (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
using System;
using System.IO;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto.Utilities;
using Org.BouncyCastle.Utilities;

/**
* ASCON AEAD v1.2, https://ascon.iaik.tugraz.at/
* https://csrc.nist.gov/CSRC/media/Projects/lightweight-cryptography/documents/finalist-round/updated-spec-doc/ascon-spec-final.pdf
* <p>
* ASCON AEAD v1.2 with reference to C Reference Impl from: https://github.com/ascon/ascon-c
* </p>
*/
namespace Org.BouncyCastle.Crypto.Engines
{
    public class AsconEngine : IAeadBlockCipher
    {
        public enum AsconParameters
        {
            ascon80pq,
            ascon128a,
            ascon128
        }

        private readonly AsconParameters asconParameters;
        private readonly MemoryStream aadData = new MemoryStream();
        private bool encrypted;
        private readonly int CRYPTO_KEYBYTES;
        private readonly int CRYPTO_ABYTES;
        private readonly int ASCON_AEAD_RATE;
        private readonly int nr;
        private ulong K0;
        private ulong K1;
        private ulong K2;
        private ulong N0;
        private ulong N1;
        private readonly ulong ASCON_IV;
        private ulong x0;
        private ulong x1;
        private ulong x2;
        private ulong x3;
        private ulong x4;

        public IBlockCipher UnderlyingCipher => throw new NotImplementedException();

        public string AlgorithmName => "ASCON AEAD";

        public AsconEngine(AsconParameters asconParameters)
        {
            this.asconParameters = asconParameters;
            switch (asconParameters)
            {
                case AsconParameters.ascon80pq:
                    CRYPTO_KEYBYTES = 20;
                    CRYPTO_ABYTES = 16;
                    ASCON_AEAD_RATE = 8;
                    ASCON_IV = 0xa0400c0600000000UL;
                    break;
                case AsconParameters.ascon128a:
                    CRYPTO_KEYBYTES = 16;
                    CRYPTO_ABYTES = 16;
                    ASCON_AEAD_RATE = 16;
                    ASCON_IV = 0x80800c0800000000UL;
                    break;
                case AsconParameters.ascon128:
                    CRYPTO_KEYBYTES = 16;
                    CRYPTO_ABYTES = 16;
                    ASCON_AEAD_RATE = 8;
                    ASCON_IV = 0x80400c0600000000UL;
                    break;
                default:
                    throw new ArgumentException("invalid parameter setting for ASCON AEAD");
            }
            nr = (ASCON_AEAD_RATE == 8) ? 6 : 8;
        }

        private ulong U64BIG(ulong x)
        {
            return (((0x00000000000000FFUL & (x)) << 56) |
            ((0x000000000000FF00UL & (x)) << 40) |
            ((0x0000000000FF0000UL & (x)) << 24) |
            ((0x00000000FF000000UL & (x)) << 8) |
            ((0x000000FF00000000UL & (x)) >> 8) |
            ((0x0000FF0000000000UL & (x)) >> 24) |
            ((0x00FF000000000000UL & (x)) >> 40) |
            ((0xFF00000000000000UL & (x)) >> 56));
        }

        private ulong ROR(ulong x, int n)
        {
            return x >> n | x << (64 - n);
        }

        private ulong KEYROT(ulong lo2hi, ulong hi2lo)
        {
            return lo2hi << 32 | hi2lo >> 32;
        }

        private ulong PAD(int i)
        {
            return 0x80UL << (56 - (i << 3));
        }

        private ulong MASK(int n)
        {
            /* undefined for n == 0 */
            return ~0UL >> (64 - (n << 3));
        }

        private ulong LOAD(byte[] bytes, int inOff, int n)
        {
            ulong x = 0;
            int len = System.Math.Min(8, bytes.Length - inOff);
            for (int i = 0; i < len; ++i)
            {
                x |= (bytes[i + inOff] & 0xFFUL) << (i << 3);
            }
            return U64BIG(x & MASK(n));
        }

        private void STORE(byte[] bytes, int inOff, ulong w, int n)
        {
            ulong x = Pack.LE_To_UInt64(bytes, inOff);
            x &= ~MASK(n);
            x |= U64BIG(w);
            Pack.UInt64_To_LE(x, bytes, inOff);
        }

        private ulong LOADBYTES(byte[] bytes, int inOff, int n)
        {
            ulong x = 0;
            for (int i = 0; i < n; ++i)
            {
                x |= (bytes[i + inOff] & 0xFFUL) << ((7 - i) << 3);
            }
            return x;
        }

        private void STOREBYTES(byte[] bytes, int inOff, ulong w, int n)
        {
            for (int i = 0; i < n; ++i)
            {
                bytes[i + inOff] = (byte)(w >> ((7 - i) << 3));
            }
        }

        private void ROUND(ulong C)
        {
            ulong t0 = x0 ^ x1 ^ x2 ^ x3 ^ C ^ (x1 & (x0 ^ x2 ^ x4 ^ C));
            ulong t1 = x0 ^ x2 ^ x3 ^ x4 ^ C ^ ((x1 ^ x2 ^ C) & (x1 ^ x3));
            ulong t2 = x1 ^ x2 ^ x4 ^ C ^ (x3 & x4);
            ulong t3 = x0 ^ x1 ^ x2 ^ C ^ ((~x0) & (x3 ^ x4));
            ulong t4 = x1 ^ x3 ^ x4 ^ ((x0 ^ x4) & x1);
            x0 = t0 ^ ROR(t0, 19) ^ ROR(t0, 28);
            x1 = t1 ^ ROR(t1, 39) ^ ROR(t1, 61);
            x2 = ~(t2 ^ ROR(t2, 1) ^ ROR(t2, 6));
            x3 = t3 ^ ROR(t3, 10) ^ ROR(t3, 17);
            x4 = t4 ^ ROR(t4, 7) ^ ROR(t4, 41);
        }

        private void P(int nr)
        {
            if (nr == 12)
            {
                ROUND(0xf0UL);
                ROUND(0xe1UL);
                ROUND(0xd2UL);
                ROUND(0xc3UL);
            }
            if (nr >= 8)
            {
                ROUND(0xb4UL);
                ROUND(0xa5UL);
            }
            ROUND(0x96UL);
            ROUND(0x87UL);
            ROUND(0x78UL);
            ROUND(0x69UL);
            ROUND(0x5aUL);
            ROUND(0x4bUL);
        }

        private void ascon_aeadinit()
        {
            /* initialize */
            x0 ^= ASCON_IV;
            if (CRYPTO_KEYBYTES == 20)
            {
                x0 ^= K0;
            }
            x1 ^= K1;
            x2 ^= K2;
            x3 ^= N0;
            x4 ^= N1;
            P(12);
            if (CRYPTO_KEYBYTES == 20)
            {
                x2 ^= K0;
            }
            x3 ^= K1;
            x4 ^= K2;
        }

        private void ascon_adata(byte[] ad, int adOff, int adlen)
        {
            if (adlen != 0)
            {
                /* full associated data blocks */
                while (adlen >= ASCON_AEAD_RATE)
                {
                    x0 ^= LOAD(ad, adOff, 8);
                    if (ASCON_AEAD_RATE == 16)
                    {
                        x1 ^= LOAD(ad, adOff + 8, 8);
                    }
                    P(nr);
                    adOff += ASCON_AEAD_RATE;
                    adlen -= ASCON_AEAD_RATE;
                }
                /* readonly associated data block */
                if (ASCON_AEAD_RATE == 16 && adlen >= 8)
                {
                    x0 ^= LOAD(ad, adOff, 8);
                    adOff += 8;
                    adlen -= 8;
                    x1 ^= PAD(adlen);
                    if (adlen != 0)
                    {
                        x1 ^= LOAD(ad, adOff, adlen);
                    }
                }
                else
                {
                    x0 ^= PAD(adlen);
                    if (adlen != 0)
                    {
                        x0 ^= LOAD(ad, adOff, adlen);
                    }
                }
                P(nr);
            }
            /* domain separation */
            x4 ^= 1UL;
        }

        private void ascon_encrypt(byte[] c, int cOff, byte[] m, int mOff, int mlen)
        {
            /* full plaintext blocks */
            while (mlen >= ASCON_AEAD_RATE)
            {
                x0 ^= LOAD(m, mOff, 8);
                STORE(c, cOff, x0, 8);
                if (ASCON_AEAD_RATE == 16)
                {
                    x1 ^= LOAD(m, mOff + 8, 8);
                    STORE(c, cOff + 8, x1, 8);
                }
                P(nr);
                mOff += ASCON_AEAD_RATE;
                cOff += ASCON_AEAD_RATE;
                mlen -= ASCON_AEAD_RATE;
            }
            /* readonly plaintext block */
            if (ASCON_AEAD_RATE == 16 && mlen >= 8)
            {
                x0 ^= LOAD(m, mOff, 8);
                STORE(c, cOff, x0, 8);
                mOff += 8;
                cOff += 8;
                mlen -= 8;
                x1 ^= PAD(mlen);
                if (mlen != 0)
                {
                    x1 ^= LOAD(m, mOff, mlen);
                    STORE(c, cOff, x1, mlen);
                }
            }
            else
            {
                x0 ^= PAD(mlen);
                if (mlen != 0)
                {
                    x0 ^= LOAD(m, mOff, mlen);
                    STORE(c, cOff, x0, mlen);
                }
            }
        }

        private void ascon_final()
        {
            /* finalize */
            switch (asconParameters)
            {
                case AsconParameters.ascon128:
                    x1 ^= K1;
                    x2 ^= K2;
                    break;
                case AsconParameters.ascon128a:
                    x2 ^= K1;
                    x3 ^= K2;
                    break;
                case AsconParameters.ascon80pq:
                    x1 ^= KEYROT(K0, K1);
                    x2 ^= KEYROT(K1, K2);
                    x3 ^= KEYROT(K2, 0UL);
                    break;
            }
            P(12);
            x3 ^= K1;
            x4 ^= K2;
        }

        public void Init(bool forEncryption, ICipherParameters param)
        {
            /**
            * ASCON encryption and decryption is completely symmetrical, so the
            * 'forEncryption' is irrelevant.
*/
            if (!(param is ParametersWithIV))
            {
                throw new ArgumentException(
                "ASCON init parameters must include an IV");
            }
            ParametersWithIV ivParams = (ParametersWithIV)param;
            byte[] npub = ivParams.GetIV();
            if (npub == null || npub.Length != CRYPTO_ABYTES)
            {
                throw new ArgumentException(asconParameters + " requires exactly " + CRYPTO_ABYTES + " bytes of IV");
            }
            if (!(ivParams.Parameters is KeyParameter))
            {
                throw new ArgumentException(
                "ASCON init parameters must include a key");
            }
            KeyParameter key = (KeyParameter)ivParams.Parameters;
            byte[] k = key.GetKey();
            if (k.Length != CRYPTO_KEYBYTES)
            {
                throw new ArgumentException(asconParameters + " key must be " + CRYPTO_KEYBYTES + " bytes long");
            }
            N0 = LOAD(npub, 0, 8);
            N1 = LOAD(npub, 8, 8);
            if (CRYPTO_KEYBYTES == 16)
            {
                K1 = LOAD(k, 0, 8);
                K2 = LOAD(k, 8, 8);
            }
            else if (CRYPTO_KEYBYTES == 20)
            {
                K0 = KEYROT(0, LOADBYTES(k, 0, 4));
                K1 = LOADBYTES(k, 4, 8);
                K2 = LOADBYTES(k, 12, 8);
            }
            /*Mask-Gen*/
            Reset();
        }

        public void ProcessAadByte(byte input)
        {
            aadData.Write(new byte[] { input }, 0, 1);
        }


        public void ProcessAadBytes(byte[] input, int inOff, int len)
        {
            aadData.Write(input, inOff, len);
        }


        public int ProcessByte(byte input, byte[] output, int outOff)
        {
            return ProcessBytes(new byte[] { input }, 0, 1, output, outOff);
        }


        public int ProcessBytes(byte[] input, int inOff, int len, byte[] output, int outOff)
        {
            if (encrypted)
            {
                throw new ArgumentException("ProcessBytes for ASCONcan be called once only");
            }
            byte[] ad = aadData.GetBuffer();
            int adlen = (int)aadData.Length;
            /* perform ascon computation */
            //ascon_aeadinit();
            ascon_adata(ad, 0, adlen);
            ascon_encrypt(output, outOff, input, inOff, len);
            ascon_final();
            encrypted = true;
            return len;
        }


        public int DoFinal(byte[] output, int outOff)
        {
            if (!encrypted)
            {
                ProcessBytes(new byte[] { }, 0, 0, new byte[] { }, 0);
            }
            /* set tag */
            STOREBYTES(output, outOff, x3, 8);
            STOREBYTES(output, outOff + 8, x4, 8);
            Reset();
            return CRYPTO_ABYTES;
        }


        public byte[] GetMac()
        {
            if (!encrypted)
            {
                ProcessBytes(new byte[] { }, 0, 0, new byte[] { }, 0);
            }
            byte[] output = new byte[CRYPTO_ABYTES];
            STOREBYTES(output, 0, x3, 8);
            STOREBYTES(output, 8, x4, 8);
            return output;
        }


        public int GetUpdateOutputSize(int len)
        {
            return len;
        }

        public int GetOutputSize(int len)
        {
            return len + CRYPTO_ABYTES;
        }


        public void Reset()
        {
            x0 = x1 = x2 = x3 = x4 = 0;
            ascon_aeadinit();
            aadData.SetLength(0);
            encrypted = false;
        }

#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
        public void ProcessAadBytes(ReadOnlySpan<byte> input)
        {
            aadData.Write(input);
        }

        public int ProcessByte(byte input, Span<byte> output)
        {
            byte[] rv = new byte[1];
            ProcessBytes(new byte[] { input }, 0, 1, rv, 0);
            rv.AsSpan(0, 1).CopyTo(output);
            return 1;
        }

        public int ProcessBytes(ReadOnlySpan<byte> input, Span<byte> output)
        {
            byte[] rv = new byte[input.Length];
            ProcessBytes(input.ToArray(), 0, rv.Length, rv, 0);
            rv.AsSpan(0, rv.Length).CopyTo(output);
            return rv.Length;
        }

        public int DoFinal(Span<byte> output)
        {
            byte[] tag = GetMac();
            tag.AsSpan(0, tag.Length).CopyTo(output);
            Reset();
            return tag.Length;
        }
#endif
        public int GetBlockSize()
        {
            return ASCON_AEAD_RATE;
        }
    }
}