2.2.1 Code Example: Generating Random Values
One of the nicest features of the JCA's SecureRandom engine is that it declares a number of helper methods that are used to generate more than just random bytes of data. This subtlety is a result of the JCA architects having the presence to define the SecureRandom engine as extending the java. util. Random class. By itself, the java. util. Random class is not suitable for cryptographic operations. However, when it is seeded using the SHA1PRNG (or another nondeterministic algorithm) as the SecureRandom engine does, it becomes acceptable for use in our cryptographic algorithms. The following code example demonstrates this functionality in action, as we generate random boolean, int and byte values:
Example 2.1 Sample Code Location: com.mkp.jce.chap2.CsprngExample
1 try
2 {
3
//Locate a SHA1PRNG provider
4
SecureRandom csprng = SecureRandom.getlnstance("SHA1PRNG");
6
//Generate a randome boolean value
■ 2.3 The Key/Generator Engine 33
7 boolean randomBoolean = csprng.nextBoolean(); 8
9 //Generate a random int value
10 int randomlnt = csprng.nextInt(); 11
12 //Generate 3 random bytes
13 byte[3] randomBytes = new byte[3];
14 csprng.nextBytes[randomBytes]; 15
16 } catch (NoSuchAlgorithmException e)
17 {
18 //Handle this!
19 e.printStackTraceO;
20 }
The engine attempts to locate a provider that implements the requested CSPRNG algorithm (SHA1PRNG in this example) on line 4 of the code example. Next, one of two things happens. In our code example, the engine automatically takes the steps necessary to completely randomize its internal state on our first random data request, in this case a call to nextBooleanQ on line 7. Alternatively, we could have invoked the setSeedQ method at line 5 immediately after locating our SecureRandom instance. This would have told the engine to use our seed instead of generating its own. However, unless you know you have access to a great random seed, it is best to let the engine initialize itself. If we wanted to further seed the engine, at anytime after line 7 we could have invoked one or more setSeedQ calls.
Now that we understand how random number sequences suitable for use in cryptographic operations are obtained, we turn our focus towards creating secret keys suitable for use in a symmetric cipher. |