summaryrefslogtreecommitdiffstats
path: root/bcprov/src/main/java/org/bouncycastle/crypto/prng/X931SecureRandom.java
blob: e51e6f042faab126e06826365510375b1639fff8 (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
package org.bouncycastle.crypto.prng;

import java.security.SecureRandom;

public class X931SecureRandom
    extends SecureRandom
{
    private final boolean predictionResistant;
    private final SecureRandom randomSource;
    private final X931RNG drbg;

    X931SecureRandom(SecureRandom randomSource, X931RNG drbg, boolean predictionResistant)
    {
        this.randomSource = randomSource;
        this.drbg = drbg;
        this.predictionResistant = predictionResistant;
    }

    public void setSeed(byte[] seed)
    {
        synchronized (this)
        {
            if (randomSource != null)
            {
                this.randomSource.setSeed(seed);
            }
        }
    }

    public void setSeed(long seed)
    {
        synchronized (this)
        {
            // this will happen when SecureRandom() is created
            if (randomSource != null)
            {
                this.randomSource.setSeed(seed);
            }
        }
    }

    public void nextBytes(byte[] bytes)
    {
        synchronized (this)
        {
            // check if a reseed is required...
            if (drbg.generate(bytes, predictionResistant) < 0)
            {
                drbg.reseed();
                drbg.generate(bytes, predictionResistant);
            }
        }
    }

    public byte[] generateSeed(int numBytes)
    {
        byte[] bytes = new byte[numBytes];

        this.nextBytes(bytes);

        return bytes;
    }
}