aboutsummaryrefslogtreecommitdiffstats
path: root/libraries/spongycastle/core/src/main/java/org/spongycastle/crypto/prng/ThreadedSeedGenerator.java
blob: fc1035423147410236d2291e3b04299ada06baf2 (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
package org.spongycastle.crypto.prng;

/**
 * A thread based seed generator - one source of randomness.
 * <p>
 * Based on an idea from Marcus Lippert.
 * </p>
 */
public class ThreadedSeedGenerator
{
    private class SeedGenerator
        implements Runnable
    {
        private volatile int counter = 0;
        private volatile boolean stop = false;

        public void run()
        {
            while (!this.stop)
            {
                this.counter++;
            }

        }

        public byte[] generateSeed(
            int numbytes,
            boolean fast)
        {
            Thread t = new Thread(this);
            byte[] result = new byte[numbytes];
            this.counter = 0;
            this.stop = false;
            int last = 0;
            int end;

            t.start();
            if(fast)
            {
                end = numbytes;
            }
            else
            {
                end = numbytes * 8;
            }
            for (int i = 0; i < end; i++)
            {
                while (this.counter == last)
                {
                    try
                    {
                        Thread.sleep(1);
                    }
                    catch (InterruptedException e)
                    {
                        // ignore
                    }
                }
                last = this.counter;
                if (fast)
                {
                    result[i] = (byte) (last & 0xff);
                }
                else
                {
                    int bytepos = i/8;
                    result[bytepos] = (byte) ((result[bytepos] << 1) | (last & 1));
                }

            }
            stop = true;
            return result;
        }
    }

    /**
     * Generate seed bytes. Set fast to false for best quality.
     * <p>
     * If fast is set to true, the code should be round about 8 times faster when
     * generating a long sequence of random bytes. 20 bytes of random values using
     * the fast mode take less than half a second on a Nokia e70. If fast is set to false,
     * it takes round about 2500 ms.
     * </p>
     * @param numBytes the number of bytes to generate
     * @param fast true if fast mode should be used
     */
    public byte[] generateSeed(
        int numBytes,
        boolean fast)
    {
        SeedGenerator gen = new SeedGenerator();

        return gen.generateSeed(numBytes, fast);
    }
}