summary refs log tree commit diff
path: root/crypto/src/pqc/crypto/lms/HSSPrivateKeyParameters.cs
blob: 447dbad2771944ae97e9bb1eebec296161b48127 (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
using System;
using System.Collections.Generic;
using System.IO;

using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.Utilities.IO;

namespace Org.BouncyCastle.Pqc.Crypto.Lms
{
    public class HssPrivateKeyParameters
        : LmsKeyParameters, ILmsContextBasedSigner
    {
        private int l;
        private bool isShard;
        private IList<LmsPrivateKeyParameters> keys;
        private IList<LmsSignature> sig;
        private long indexLimit;
        private long index = 0;

        private HssPublicKeyParameters publicKey;

        public HssPrivateKeyParameters(int l, IList<LmsPrivateKeyParameters> keys, IList<LmsSignature> sig, long index,
            long indexLimit)
    	    :base(true)
        {
            this.l = l;
            this.keys = new List<LmsPrivateKeyParameters>(keys);
            this.sig = new List<LmsSignature>(sig);
            this.index = index;
            this.indexLimit = indexLimit;
            this.isShard = false;

            //
            // Correct Intermediate LMS values will be constructed during reset to index.
            //
            ResetKeyToIndex();
        }

        private HssPrivateKeyParameters(int l, IList<LmsPrivateKeyParameters> keys, IList<LmsSignature> sig, long index,
            long indexLimit, bool isShard)
    	    :base(true)
        {

            this.l = l;
            // this.keys =  new UnmodifiableListProxy(keys);
            // this.sig =  new UnmodifiableListProxy(sig);
            this.keys = new List<LmsPrivateKeyParameters>(keys);
            this.sig = new List<LmsSignature>(sig);
            this.index = index;
            this.indexLimit = indexLimit;
            this.isShard = isShard;
        }

        public static HssPrivateKeyParameters GetInstance(byte[] privEnc, byte[] pubEnc)
        {
            HssPrivateKeyParameters pKey = GetInstance(privEnc);

            pKey.publicKey = HssPublicKeyParameters.GetInstance(pubEnc);

            return pKey;
        }

        public static HssPrivateKeyParameters GetInstance(object src)
        {
            if (src is HssPrivateKeyParameters hssPrivateKeyParameters)
            {
                return hssPrivateKeyParameters;
            }
            else if (src is BinaryReader binaryReader)
            {
                int version = BinaryReaders.ReadInt32BigEndian(binaryReader);
                if (version != 0)
                    throw new Exception("unknown version for HSS private key");

                int d = BinaryReaders.ReadInt32BigEndian(binaryReader);

                long index = BinaryReaders.ReadInt64BigEndian(binaryReader);

                long maxIndex = BinaryReaders.ReadInt64BigEndian(binaryReader);

                bool limited = binaryReader.ReadBoolean();

                var keys = new List<LmsPrivateKeyParameters>();
                var signatures = new List<LmsSignature>();

                for (int t = 0; t < d; t++)
                {
                    keys.Add(LmsPrivateKeyParameters.GetInstance(src));
                }

                for (int t = 0; t < d - 1; t++)
                {
                    signatures.Add(LmsSignature.GetInstance(src));
                }

                return new HssPrivateKeyParameters(d, keys, signatures, index, maxIndex, limited);
            }
            else if (src is byte[] bytes)
            {
                BinaryReader input = null;
                try // 1.5 / 1.6 compatibility
                {
                    input = new BinaryReader(new MemoryStream(bytes));
                    return GetInstance(input);
                }
                finally
                {
                    if (input != null)
                    {
                        input.Close();
                    }
                }
            }
            else if (src is MemoryStream memoryStream)
            {
                return GetInstance(Streams.ReadAll(memoryStream));
            }

            throw new Exception($"cannot parse {src}");
        }

        public int L => l;

        public long GetIndex()
        {
            lock (this)
                return index;
        }

        public LmsParameters[] GetLmsParameters()
        {
            lock (this)
            {
                int len = keys.Count;

                LmsParameters[] parms = new LmsParameters[len];

                for (int i = 0; i < len; i++)
                {
                    LmsPrivateKeyParameters lmsPrivateKey = keys[i];

                    parms[i] = new LmsParameters(lmsPrivateKey.GetSigParameters(), lmsPrivateKey.GetOtsParameters());
                }

                return parms;
            }
        }

        internal void IncIndex()
        {
            lock (this)
            {
                index++;
            }
        }

        private static HssPrivateKeyParameters MakeCopy(HssPrivateKeyParameters privateKeyParameters)
        {
            return GetInstance(privateKeyParameters.GetEncoded());
        }

        protected void UpdateHierarchy(IList<LmsPrivateKeyParameters> newKeys, IList<LmsSignature> newSig)
        {
            lock (this)
            {
                keys = new List<LmsPrivateKeyParameters>(newKeys);
                sig = new List<LmsSignature>(newSig);
            }
        }

        public bool IsShard()
        {
            return isShard;
        }

        public long IndexLimit => indexLimit;

        public long GetUsagesRemaining()
        {
            return indexLimit - index;
        }

        LmsPrivateKeyParameters GetRootKey()
        {
            return keys[0];
        }

        /**
         * Return a key that can be used usageCount times.
         * <p>
         * Note: this will use the range [index...index + usageCount) for the current key.
         * </p>
         *
         * @param usageCount the number of usages the key should have.
         * @return a key based on the current key that can be used usageCount times.
         */
        public HssPrivateKeyParameters ExtractKeyShard(int usageCount)
        {
            lock (this)
            {
                if (GetUsagesRemaining() < usageCount)
                    throw new ArgumentException("usageCount exceeds usages remaining in current leaf");

                long maxIndexForShard = index + usageCount;
                long shardStartIndex = index;

                //
                // Move this key's index along
                //
                index += usageCount;

                var keys = new List<LmsPrivateKeyParameters>(this.GetKeys());
                var sig = new List<LmsSignature>(this.GetSig());

                HssPrivateKeyParameters shard = MakeCopy(
                    new HssPrivateKeyParameters(l, keys, sig, shardStartIndex, maxIndexForShard, true));

                ResetKeyToIndex();

                return shard;
            }
        }

        public IList<LmsPrivateKeyParameters> GetKeys()
        {
            lock (this) return keys;
        }

        internal IList<LmsSignature> GetSig()
        {
            lock (this) return sig;
        }

        /**
         * Reset to index will ensure that all LMS keys are correct for a given HSS index value.
         * Normally LMS keys updated in sync with their parent HSS key but in cases of sharding
         * the normal monotonic updating does not apply and the state of the LMS keys needs to be
         * reset to match the current HSS index.
         */
        void ResetKeyToIndex()
        {
            // Extract the original keys
            var originalKeys = GetKeys();

            long[] qTreePath = new long[originalKeys.Count];
            long q = GetIndex();

            for (int t = originalKeys.Count - 1; t >= 0; t--)
            {
                LMSigParameters sigParameters = originalKeys[t].GetSigParameters();
                int mask = (1 << sigParameters.H) - 1;
                qTreePath[t] = q & mask;
                q >>= sigParameters.H;
            }

            bool changed = false;

            // LMSPrivateKeyParameters[] keys =  originalKeys.ToArray(new LMSPrivateKeyParameters[originalKeys.Count]);//  new LMSPrivateKeyParameters[originalKeys.Size()];
            // LMSSignature[] sig = this.sig.toArray(new LMSSignature[this.sig.Count]);//   new LMSSignature[originalKeys.Size() - 1];
            //

            LmsPrivateKeyParameters originalRootKey = this.GetRootKey();

            //
            // We need to replace the root key to a new q value.
            //
            if (keys[0].GetIndex() - 1 != qTreePath[0])
            {
                keys[0] = Lms.GenerateKeys(
                    originalRootKey.GetSigParameters(),
                    originalRootKey.GetOtsParameters(),
                    (int)qTreePath[0], originalRootKey.GetI(), originalRootKey.GetMasterSecret());
                changed = true;
            }

            for (int i = 1; i < qTreePath.Length; i++)
            {
                LmsPrivateKeyParameters intermediateKey = keys[i - 1];

                byte[] childI = new byte[16];
                byte[] childSeed = new byte[32];
                SeedDerive derive = new SeedDerive(
                    intermediateKey.GetI(),
                    intermediateKey.GetMasterSecret(),
                    DigestUtilities.GetDigest(intermediateKey.GetOtsParameters().DigestOid))
                {
                    Q = (int)qTreePath[i - 1],
                    J = ~1,
                };

                derive.DeriveSeed(true, childSeed, 0);
                byte[] postImage = new byte[32];
                derive.DeriveSeed(false, postImage, 0);
                Array.Copy(postImage, 0, childI, 0, childI.Length);

                //
                // Q values in LMS keys post increment after they are used.
                // For intermediate keys they will always be out by one from the derived q value (qValues[i])
                // For the end key its value will match so no correction is required.
                //
                bool lmsQMatch = (i < qTreePath.Length - 1)
                    ? qTreePath[i] == keys[i].GetIndex() - 1
                    : qTreePath[i] == keys[i].GetIndex();

                //
                // Equality is I and seed being equal and the lmsQMath.
                // I and seed are derived from this nodes parent and will change if the parent q, I, seed changes.
                //
                bool seedEquals = Arrays.AreEqual(childI, keys[i].GetI())
                    && Arrays.AreEqual(childSeed, keys[i].GetMasterSecret());

                if (!seedEquals)
                {
                    //
                    // This means the parent has changed.
                    //
                    keys[i] = Lms.GenerateKeys(
                        originalKeys[i].GetSigParameters(),
                        originalKeys[i].GetOtsParameters(),
                        (int)qTreePath[i], childI, childSeed);

                    //
                    // Ensure post increment occurs on parent and the new public key is signed.
                    //
                    sig[i - 1] = Lms.GenerateSign((LmsPrivateKeyParameters)keys[i - 1], ((LmsPrivateKeyParameters)keys[i]).GetPublicKey().ToByteArray());
                    changed = true;
                }
                else if (!lmsQMatch)
                {
                    //
                    // Q is different so we can generate a new private key but it will have the same public
                    // key so we do not need to sign it again.
                    //
                    keys[i] = Lms.GenerateKeys(
                        originalKeys[i].GetSigParameters(),
                        originalKeys[i].GetOtsParameters(),
                        (int)qTreePath[i], childI, childSeed);
                    changed = true;
                }
            }

            if (changed)
            {
                // We mutate the HSS key here!
                UpdateHierarchy(keys, sig);
            }
        }

        public HssPublicKeyParameters GetPublicKey()
        {
            lock (this)
                return new HssPublicKeyParameters(l, GetRootKey().GetPublicKey());
        }

        internal void ReplaceConsumedKey(int d)
        {
            SeedDerive deriver = keys[d - 1].GetCurrentOtsKey().GetDerivationFunction();
            deriver.J = ~1;
            byte[] childRootSeed = new byte[32];
            deriver.DeriveSeed(true, childRootSeed, 0);
            byte[] postImage = new byte[32];
            deriver.DeriveSeed(false, postImage, 0);
            byte[] childI = new byte[16];
            Array.Copy(postImage, 0, childI, 0, childI.Length);

            var newKeys = new List<LmsPrivateKeyParameters>(keys);

            //
            // We need the parameters from the LMS key we are replacing.
            //
            LmsPrivateKeyParameters oldPk = keys[d];

            newKeys[d] = Lms.GenerateKeys(oldPk.GetSigParameters(), oldPk.GetOtsParameters(), 0, childI, childRootSeed);

            var newSig = new List<LmsSignature>(sig);

            newSig[d - 1] = Lms.GenerateSign(newKeys[d - 1], newKeys[d].GetPublicKey().ToByteArray());

            this.keys = new List<LmsPrivateKeyParameters>(newKeys);
            this.sig = new List<LmsSignature>(newSig);
        }

        public override bool Equals(Object o)
        {
            if (this == o)
            {
                return true;
            }
            if (o == null || GetType() != o.GetType())
            {
                return false;
            }

            HssPrivateKeyParameters that = (HssPrivateKeyParameters)o;

            if (l != that.l)
            {
                return false;
            }
            if (isShard != that.isShard)
            {
                return false;
            }
            if (indexLimit != that.indexLimit)
            {
                return false;
            }
            if (index != that.index)
            {
                return false;
            }
            if (!CompareLists(keys, that.keys))
            {
                return false;
            }
            return CompareLists(sig, that.sig);
        }

        private bool CompareLists<T>(IList<T> arr1, IList<T> arr2)
        {
            for (int i=0; i<arr1.Count && i<arr2.Count; i++)
            {
                if (!Object.Equals(arr1[i], arr2[i]))
                {
                    return false;
                }
            }
            return true;
        }
        

        public override byte[] GetEncoded()
        {
            lock (this)
            {
                //
                // Private keys are implementation dependent.
                //

                Composer composer = Composer.Compose()
                    .U32Str(0) // Version.
                    .U32Str(l)
                    .U64Str(index)
                    .U64Str(indexLimit)
                    .Boolean(isShard); // Depth

                foreach (LmsPrivateKeyParameters key in keys)
                {
                    composer.Bytes(key);
                }

                foreach (LmsSignature s in sig)
                {
                    composer.Bytes(s);
                }

                return composer.Build();
            }
        }

        public override int GetHashCode()
        {
            int result = l;
            result = 31 * result + (isShard ? 1 : 0);
            result = 31 * result + keys.GetHashCode();
            result = 31 * result + sig.GetHashCode();
            result = 31 * result + (int)(indexLimit ^ (indexLimit >> 32));
            result = 31 * result + (int)(index ^ (index >> 32));
            return result;
        }

        protected object Clone()
        {
            return MakeCopy(this);
        }

        public LmsContext GenerateLmsContext()
        {
            LmsSignedPubKey[] signed_pub_key;
            LmsPrivateKeyParameters nextKey;
            int L = this.L;

            lock (this)
            {
                Hss.RangeTestKeys(this);

                var keys = this.GetKeys();
                var sig = this.GetSig();

                nextKey = this.GetKeys()[L - 1];

                // Step 2. Stand in for sig[L-1]
                int i = 0;
                signed_pub_key = new LmsSignedPubKey[L - 1];
                while (i < L - 1)
                {
                    signed_pub_key[i] = new LmsSignedPubKey(sig[i], keys[i + 1].GetPublicKey());
                    ++i;
                }

                //
                // increment the index.
                //
                this.IncIndex();
            }

            return nextKey.GenerateLmsContext().WithSignedPublicKeys(signed_pub_key);
        }

        public byte[] GenerateSignature(LmsContext context)
        {
            try
            {
                return Hss.GenerateSignature(L, context).GetEncoded();
            }
            catch (IOException e)
            {
                throw new Exception($"unable to encode signature: {e.Message}", e);
            }
        }
    }
}