Welcome to mirror list, hosted at ThFree Co, Russian Federation.

GMSSKeyPairGenerator.java « gmss « crypto « pqc « spongycastle « org « java « main « src « core - gitlab.com/quite/humla-spongycastle.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: bb1ef36dd18f8ff9b3deed341759b5b7a34697f7 (plain)
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
package org.spongycastle.pqc.crypto.gmss;

import java.security.SecureRandom;
import java.util.Vector;

import org.spongycastle.crypto.AsymmetricCipherKeyPair;
import org.spongycastle.crypto.AsymmetricCipherKeyPairGenerator;
import org.spongycastle.crypto.Digest;
import org.spongycastle.crypto.KeyGenerationParameters;
import org.spongycastle.pqc.crypto.gmss.util.GMSSRandom;
import org.spongycastle.pqc.crypto.gmss.util.WinternitzOTSVerify;
import org.spongycastle.pqc.crypto.gmss.util.WinternitzOTSignature;


/**
 * This class implements key pair generation of the generalized Merkle signature
 * scheme (GMSS).
 *
 * @see GMSSSigner
 */
public class GMSSKeyPairGenerator
    implements AsymmetricCipherKeyPairGenerator
{
    /**
     * The source of randomness for OTS private key generation
     */
    private GMSSRandom gmssRandom;

    /**
     * The hash function used for the construction of the authentication trees
     */
    private Digest messDigestTree;

    /**
     * An array of the seeds for the PRGN (for main tree, and all current
     * subtrees)
     */
    private byte[][] currentSeeds;

    /**
     * An array of seeds for the PRGN (for all subtrees after next)
     */
    private byte[][] nextNextSeeds;

    /**
     * An array of the RootSignatures
     */
    private byte[][] currentRootSigs;

    /**
     * Class of hash function to use
     */
    private GMSSDigestProvider digestProvider;

    /**
     * The length of the seed for the PRNG
     */
    private int mdLength;

    /**
     * the number of Layers
     */
    private int numLayer;


    /**
     * Flag indicating if the class already has been initialized
     */
    private boolean initialized = false;

    /**
     * Instance of GMSSParameterset
     */
    private GMSSParameters gmssPS;

    /**
     * An array of the heights of the authentication trees of each layer
     */
    private int[] heightOfTrees;

    /**
     * An array of the Winternitz parameter 'w' of each layer
     */
    private int[] otsIndex;

    /**
     * The parameter K needed for the authentication path computation
     */
    private int[] K;

    private GMSSKeyGenerationParameters gmssParams;

    /**
     * The GMSS OID.
     */
    public static final String OID = "1.3.6.1.4.1.8301.3.1.3.3";

    /**
     * The standard constructor tries to generate the GMSS algorithm identifier
     * with the corresponding OID.
     *
     * @param digestProvider     provider for digest implementations.
     */
    public GMSSKeyPairGenerator(GMSSDigestProvider digestProvider)
    {
        this.digestProvider = digestProvider;
        messDigestTree = digestProvider.get();

        // set mdLength
        this.mdLength = messDigestTree.getDigestSize();
        // construct randomizer
        this.gmssRandom = new GMSSRandom(messDigestTree);

    }

    /**
     * Generates the GMSS key pair. The public key is an instance of
     * JDKGMSSPublicKey, the private key is an instance of JDKGMSSPrivateKey.
     *
     * @return Key pair containing a JDKGMSSPublicKey and a JDKGMSSPrivateKey
     */
    private AsymmetricCipherKeyPair genKeyPair()
    {
        if (!initialized)
        {
            initializeDefault();
        }

        // initialize authenticationPaths and treehash instances
        byte[][][] currentAuthPaths = new byte[numLayer][][];
        byte[][][] nextAuthPaths = new byte[numLayer - 1][][];
        Treehash[][] currentTreehash = new Treehash[numLayer][];
        Treehash[][] nextTreehash = new Treehash[numLayer - 1][];

        Vector[] currentStack = new Vector[numLayer];
        Vector[] nextStack = new Vector[numLayer - 1];

        Vector[][] currentRetain = new Vector[numLayer][];
        Vector[][] nextRetain = new Vector[numLayer - 1][];

        for (int i = 0; i < numLayer; i++)
        {
            currentAuthPaths[i] = new byte[heightOfTrees[i]][mdLength];
            currentTreehash[i] = new Treehash[heightOfTrees[i] - K[i]];

            if (i > 0)
            {
                nextAuthPaths[i - 1] = new byte[heightOfTrees[i]][mdLength];
                nextTreehash[i - 1] = new Treehash[heightOfTrees[i] - K[i]];
            }

            currentStack[i] = new Vector();
            if (i > 0)
            {
                nextStack[i - 1] = new Vector();
            }
        }

        // initialize roots
        byte[][] currentRoots = new byte[numLayer][mdLength];
        byte[][] nextRoots = new byte[numLayer - 1][mdLength];
        // initialize seeds
        byte[][] seeds = new byte[numLayer][mdLength];
        // initialize seeds[] by copying starting-seeds of first trees of each
        // layer
        for (int i = 0; i < numLayer; i++)
        {
            System.arraycopy(currentSeeds[i], 0, seeds[i], 0, mdLength);
        }

        // initialize rootSigs
        currentRootSigs = new byte[numLayer - 1][mdLength];

        // -------------------------
        // -------------------------
        // --- calculation of current authpaths and current rootsigs (AUTHPATHS,
        // SIG)------
        // from bottom up to the root
        for (int h = numLayer - 1; h >= 0; h--)
        {
            GMSSRootCalc tree = new GMSSRootCalc(this.heightOfTrees[h], this.K[h], digestProvider);
            try
            {
                // on lowest layer no lower root is available, so just call
                // the method with null as first parameter
                if (h == numLayer - 1)
                {
                    tree = this.generateCurrentAuthpathAndRoot(null, currentStack[h], seeds[h], h);
                }
                else
                // otherwise call the method with the former computed root
                // value
                {
                    tree = this.generateCurrentAuthpathAndRoot(currentRoots[h + 1], currentStack[h], seeds[h], h);
                }

            }
            catch (Exception e1)
            {
                e1.printStackTrace();
            }

            // set initial values needed for the private key construction
            for (int i = 0; i < heightOfTrees[h]; i++)
            {
                System.arraycopy(tree.getAuthPath()[i], 0, currentAuthPaths[h][i], 0, mdLength);
            }
            currentRetain[h] = tree.getRetain();
            currentTreehash[h] = tree.getTreehash();
            System.arraycopy(tree.getRoot(), 0, currentRoots[h], 0, mdLength);
        }

        // --- calculation of next authpaths and next roots (AUTHPATHS+, ROOTS+)
        // ------
        for (int h = numLayer - 2; h >= 0; h--)
        {
            GMSSRootCalc tree = this.generateNextAuthpathAndRoot(nextStack[h], seeds[h + 1], h + 1);

            // set initial values needed for the private key construction
            for (int i = 0; i < heightOfTrees[h + 1]; i++)
            {
                System.arraycopy(tree.getAuthPath()[i], 0, nextAuthPaths[h][i], 0, mdLength);
            }
            nextRetain[h] = tree.getRetain();
            nextTreehash[h] = tree.getTreehash();
            System.arraycopy(tree.getRoot(), 0, nextRoots[h], 0, mdLength);

            // create seed for the Merkle tree after next (nextNextSeeds)
            // SEEDs++
            System.arraycopy(seeds[h + 1], 0, this.nextNextSeeds[h], 0, mdLength);
        }
        // ------------

        // generate JDKGMSSPublicKey
        GMSSPublicKeyParameters publicKey = new GMSSPublicKeyParameters(currentRoots[0], gmssPS);

        // generate the JDKGMSSPrivateKey
        GMSSPrivateKeyParameters privateKey = new GMSSPrivateKeyParameters(currentSeeds, nextNextSeeds, currentAuthPaths,
            nextAuthPaths, currentTreehash, nextTreehash, currentStack, nextStack, currentRetain, nextRetain, nextRoots, currentRootSigs, gmssPS, digestProvider);

        // return the KeyPair
        return (new AsymmetricCipherKeyPair(publicKey, privateKey));
    }

    /**
     * calculates the authpath for tree in layer h which starts with seed[h]
     * additionally computes the rootSignature of underlaying root
     *
     * @param currentStack stack used for the treehash instance created by this method
     * @param lowerRoot    stores the root of the lower tree
     * @param seed        starting seeds
     * @param h            actual layer
     */
    private GMSSRootCalc generateCurrentAuthpathAndRoot(byte[] lowerRoot, Vector currentStack, byte[] seed, int h)
    {
        byte[] help = new byte[mdLength];

        byte[] OTSseed = new byte[mdLength];
        OTSseed = gmssRandom.nextSeed(seed);

        WinternitzOTSignature ots;

        // data structure that constructs the whole tree and stores
        // the initial values for treehash, Auth and retain
        GMSSRootCalc treeToConstruct = new GMSSRootCalc(this.heightOfTrees[h], this.K[h], digestProvider);

        treeToConstruct.initialize(currentStack);

        // generate the first leaf
        if (h == numLayer - 1)
        {
            ots = new WinternitzOTSignature(OTSseed, digestProvider.get(), otsIndex[h]);
            help = ots.getPublicKey();
        }
        else
        {
            // for all layers except the lowest, generate the signature of the
            // underlying root
            // and reuse this signature to compute the first leaf of acual layer
            // more efficiently (by verifiing the signature)
            ots = new WinternitzOTSignature(OTSseed, digestProvider.get(), otsIndex[h]);
            currentRootSigs[h] = ots.getSignature(lowerRoot);
            WinternitzOTSVerify otsver = new WinternitzOTSVerify(digestProvider.get(), otsIndex[h]);
            help = otsver.Verify(lowerRoot, currentRootSigs[h]);
        }
        // update the tree with the first leaf
        treeToConstruct.update(help);

        int seedForTreehashIndex = 3;
        int count = 0;

        // update the tree 2^(H) - 1 times, from the second to the last leaf
        for (int i = 1; i < (1 << this.heightOfTrees[h]); i++)
        {
            // initialize the seeds for the leaf generation with index 3 * 2^h
            if (i == seedForTreehashIndex && count < this.heightOfTrees[h] - this.K[h])
            {
                treeToConstruct.initializeTreehashSeed(seed, count);
                seedForTreehashIndex *= 2;
                count++;
            }

            OTSseed = gmssRandom.nextSeed(seed);
            ots = new WinternitzOTSignature(OTSseed, digestProvider.get(), otsIndex[h]);
            treeToConstruct.update(ots.getPublicKey());
        }

        if (treeToConstruct.wasFinished())
        {
            return treeToConstruct;
        }
        System.err.println("Baum noch nicht fertig konstruiert!!!");
        return null;
    }

    /**
     * calculates the authpath and root for tree in layer h which starts with
     * seed[h]
     *
     * @param nextStack stack used for the treehash instance created by this method
     * @param seed      starting seeds
     * @param h         actual layer
     */
    private GMSSRootCalc generateNextAuthpathAndRoot(Vector nextStack, byte[] seed, int h)
    {
        byte[] OTSseed = new byte[numLayer];
        WinternitzOTSignature ots;

        // data structure that constructs the whole tree and stores
        // the initial values for treehash, Auth and retain
        GMSSRootCalc treeToConstruct = new GMSSRootCalc(this.heightOfTrees[h], this.K[h], this.digestProvider);
        treeToConstruct.initialize(nextStack);

        int seedForTreehashIndex = 3;
        int count = 0;

        // update the tree 2^(H) times, from the first to the last leaf
        for (int i = 0; i < (1 << this.heightOfTrees[h]); i++)
        {
            // initialize the seeds for the leaf generation with index 3 * 2^h
            if (i == seedForTreehashIndex && count < this.heightOfTrees[h] - this.K[h])
            {
                treeToConstruct.initializeTreehashSeed(seed, count);
                seedForTreehashIndex *= 2;
                count++;
            }

            OTSseed = gmssRandom.nextSeed(seed);
            ots = new WinternitzOTSignature(OTSseed, digestProvider.get(), otsIndex[h]);
            treeToConstruct.update(ots.getPublicKey());
        }

        if (treeToConstruct.wasFinished())
        {
            return treeToConstruct;
        }
        System.err.println("N�chster Baum noch nicht fertig konstruiert!!!");
        return null;
    }

    /**
     * This method initializes the GMSS KeyPairGenerator using an integer value
     * <code>keySize</code> as input. It provides a simple use of the GMSS for
     * testing demands.
     * <p>
     * A given <code>keysize</code> of less than 10 creates an amount 2^10
     * signatures. A keySize between 10 and 20 creates 2^20 signatures. Given an
     * integer greater than 20 the key pair generator creates 2^40 signatures.
     *
     * @param keySize      Assigns the parameters used for the GMSS signatures. There are
     *                     3 choices:<br>
     *                     1. keysize &lt;= 10: creates 2^10 signatures using the
     *                     parameterset<br>
     *                     P = (2, (5, 5), (3, 3), (3, 3))<br>
     *                     2. keysize &gt; 10 and &lt;= 20: creates 2^20 signatures using the
     *                     parameterset<br>
     *                     P = (2, (10, 10), (5, 4), (2, 2))<br>
     *                     3. keysize &gt; 20: creates 2^40 signatures using the
     *                     parameterset<br>
     *                     P = (2, (10, 10, 10, 10), (9, 9, 9, 3), (2, 2, 2, 2))
     * @param secureRandom not used by GMSS, the SHA1PRNG of the SUN Provider is always
     *                     used
     */
    public void initialize(int keySize, SecureRandom secureRandom)
    {

        KeyGenerationParameters kgp;
        if (keySize <= 10)
        { // create 2^10 keys
            int[] defh = {10};
            int[] defw = {3};
            int[] defk = {2};
            // XXX sec random neede?
            kgp = new GMSSKeyGenerationParameters(secureRandom, new GMSSParameters(defh.length, defh, defw, defk));
        }
        else if (keySize <= 20)
        { // create 2^20 keys
            int[] defh = {10, 10};
            int[] defw = {5, 4};
            int[] defk = {2, 2};
            kgp = new GMSSKeyGenerationParameters(secureRandom, new GMSSParameters(defh.length, defh, defw, defk));
        }
        else
        { // create 2^40 keys, keygen lasts around 80 seconds
            int[] defh = {10, 10, 10, 10};
            int[] defw = {9, 9, 9, 3};
            int[] defk = {2, 2, 2, 2};
            kgp = new GMSSKeyGenerationParameters(secureRandom, new GMSSParameters(defh.length, defh, defw, defk));
        }

        // call the initializer with the chosen parameters
        this.initialize(kgp);

    }


    /**
     * Initalizes the key pair generator using a parameter set as input
     */
    public void initialize(KeyGenerationParameters param)
    {

        this.gmssParams = (GMSSKeyGenerationParameters)param;

        // generate GMSSParameterset
        this.gmssPS = new GMSSParameters(gmssParams.getParameters().getNumOfLayers(), gmssParams.getParameters().getHeightOfTrees(),
            gmssParams.getParameters().getWinternitzParameter(), gmssParams.getParameters().getK());

        this.numLayer = gmssPS.getNumOfLayers();
        this.heightOfTrees = gmssPS.getHeightOfTrees();
        this.otsIndex = gmssPS.getWinternitzParameter();
        this.K = gmssPS.getK();

        // seeds
        this.currentSeeds = new byte[numLayer][mdLength];
        this.nextNextSeeds = new byte[numLayer - 1][mdLength];

        // construct SecureRandom for initial seed generation
        SecureRandom secRan = new SecureRandom();

        // generation of initial seeds
        for (int i = 0; i < numLayer; i++)
        {
            secRan.nextBytes(currentSeeds[i]);
            gmssRandom.nextSeed(currentSeeds[i]);
        }

        this.initialized = true;
    }

    /**
     * This method is called by generateKeyPair() in case that no other
     * initialization method has been called by the user
     */
    private void initializeDefault()
    {
        int[] defh = {10, 10, 10, 10};
        int[] defw = {3, 3, 3, 3};
        int[] defk = {2, 2, 2, 2};

        KeyGenerationParameters kgp = new GMSSKeyGenerationParameters(new SecureRandom(), new GMSSParameters(defh.length, defh, defw, defk));
        this.initialize(kgp);

    }

    public void init(KeyGenerationParameters param)
    {
        this.initialize(param);

    }

    public AsymmetricCipherKeyPair generateKeyPair()
    {
        return genKeyPair();
    }
}