A Java API Package java.security

advertisement
A Java API Package
java.security
 The Java Security Package contains classes
and interfaces that are required by many Java
programs.
 This package is imported by compiler into all
programs
Java SE 8 for Programmers
Paul Deitel &Harvey Deitel
Deitel Developer Series 2014
Case Study: Secure Random-Number
Generation
A popular type of programming application is
simulation and game playing.
The element of chance can be introduced in a
program via an object of class
SecureRandom (package java.security).
Such objects can produce random boolean,
byte, float, double, int, long values.
Class SecureRandom
java.lang.Object
java.util.Random
java.security.SecureRandom
public class SecureRandom extends Random
Random class is in java.utility
 This class provides a cryptographically strong
random number generator (RNG).
Moving to Secure Random Numbers
from Random Numbers
Java’s Random class is used to obtain
“random” values.
This class produces deterministic values that
could be predicted by malicious programmers.
SecureRandom objects produce
nondeterministic random numbers that
cannot be predicted.
A Note About Performance
Using SecureRandom instead of Random to
achieve higher levels of security incurs a
significant performance penalty.
It is possible to use class Random from package
java.util
It is required simply to replace SecureRandom with
Random.
Creating a SecureRandom Object
A new secure random-number generator object can be created
as
SecureRandom randomNumbers =
new SecureRandom();
 It can then be used to generate random
 For more information on the SecureRandom class
docs.oracle.com/javase/7/docs/api/java/security/SecureRandom.html
Obtaining a Random int Value
Consider the following statement
int randomValue = randomNumbers.nextInt();
SecureRandom method nextInt generates a random
int value.
If it truly produces values at random, then every
value in the range should have an equal chance (or
probability) of being chosen each time nextInt is
called
Changing the Range of Values
Produced By nextInt
The range of values is produced by method
nextInt
The method nextInt generally differs from the
range of values required in any Java application.
A program that simulates coin tossing might
require only 0 for “heads” and 1 for “tails.”
 A program that simulates the rolling of a sixsided die might require random integers in the
range 1–6.
Changing the Range of Values
Produced By nextInt
class SecureRandom provides another version
of method nextInt that receives an int argument
and returns a value from 0 up to, but not
including, the argument’s value.
For coin tossing, the following statement
returns 0 or 1.
int randomValue =
randomNumbers.nextInt(2);
Rolling a Six-Sided Die
 The program simulates 20 rolls of a six-sided die and displays the
value of each roll.
 nextInt produces random values in the range 0–5
int face = randomNumbers.nextInt(6);
 The argument 6 is scaling factor
the number of values that nextInt should produce (0, 1, 2,
3, 4 ,5).
 This manipulation is called scaling the range of values produced
by SecureRandom method nextInt.
 A six-sided die has the numbers 1–6 on its faces, not 0–5.
 shift the range of numbers produced by adding a shifting
value
int face = 1 + randomNumbers.nextInt(6);
The shifting value (1) specifies the first value in the desired
range of random integers. The preceding statement assigns
face a random integer in the range 1–6.
import java.security.SecureRandom;
// imports class SecureRandom from the java.security package.
public class RandomIntegers {
//each run of the program can produce a different sequence of random numbers
public static void main(String[] args) {
// creates the SecureRandom object randomNumbers to produce random values
SecureRandom randomNumbers = new SecureRandom();
// loop 20 times
for (int counter = 1; counter <= 20; counter++)
{ // pick random integer from 1 to 6
int face = 1 + randomNumbers.nextInt(6);
System.out.printf("%d ", face); // display generated value
// statement in the loop starts a new line of output after every five numbers
if (counter % 5 == 0)
System.out.println();
} }
} // end class
Shifted and Scaled Random Integers.
1
5
4
3
5
2
4
1
3
6
4
6
6
5
2
2
2
2
6
2
6
1
6
6
5
2
3
4
4
5
2
2
2
1
2
6
6
3
1
4
Rolling a Six-Sided Die 6,000,000 Times
import java.security.SecureRandom;
public class RollDie
{ public static void main(String[] args)
{
// randomNumbers object will produce secure random numbers
SecureRandom randomNumbers = new SecureRandom();
int frequency1 = 0; // count of 1s rolled
int frequency2 = 0; // count of 2s rolled
int frequency3 = 0; // count of 3s rolled
int frequency4 = 0; // count of 4s rolled
int frequency5 = 0; // count of 5s rolled
int frequency6 = 0; // count of 6s rolled
// tally counts for 6,000,000 rolls of a die
……
for (int roll = 1; roll <= 6000000; roll++)
{
int face = 1 + randomNumbers.nextInt(6);
……….;
// number from 1 to 6
switch (face) {
case 1:
…… ;
 Scaling and shifting the values produced by nextInt
enables the program to simulate rolling a six-sided die.
……
// use face value 1-6 to determine which counter to increment
switch (face) {
case 1:
++frequency1; // increment the 1s counter
break;
case 2:
++frequency2; // increment the 2s counter
break;
case 3:
++frequency3; // increment the 3s counter
break;
case 4:
++frequency4; // increment the 4s counter
break;
case 5:
++frequency5; // increment the 5s counter
break;
case 6:
++frequency6; // increment the 6s counter
break; }
Nested Control Statements
for & switch case
 The
switch is nested inside the for to determine the
number of times each side of the die appears.
The for statement iterates 6,000,000 times.
 During each iteration produces a random value from 1
to 6.
This value is used as the controlling expression of the
switch statement
Based on the face value, the switch statement
increments one of the six counter variables during each
iteration of the loop.
The switch statement has no default case, because we
have a case for every possible die value
Every time this program is run , it produces different
results.
…….
} //end for statement
System.out.println("Face\tFrequency"); // output headers
System.out.printf("1\t%d%n2\t%d%n3\t%d%n4\t%d%n5\t%
d%n6\t%d%n", frequency1, frequency2, frequency3,
frequency4, frequency5, frequency6);
} //end main program
} // end class RollDie
Roll a six-sided die 6,000,000 times
Face Frequency
1 999501
2 1000412
3 998262
4 1000820
5 1002245
6 998760
Face Frequency
1 999647
2 999557
3 999571
4 1000376
5 1000701
6 1000148
Generalized Scaling and Shifting of Random
Numbers
The rolling of a six-sided die is simulated with the
statement
int face = 1 + randomNumbers.nextInt(6);
This statement always assigns to variable face an
integer in the range 1 ≤ face ≤ 6.
The width of the range is determined by the number 6
This number is passed as an argument to SecureRandom
method nextInt
The starting number in the range is 1.
The starting number 1 of the range is added to
randomNumbers.nextInt(6)
Generalized Scaling and Shifting of Random
Numbers
int number = shiftingValue +
randomNumbers.nextInt(scalingFactor);
shiftingValue specifies the first number in the
desired range of consecutive integers
scalingFactor specifies how many numbers are in
the range.
Generalized Scaling and Shifting of
Random Numbers
It’s possible to choose integers at random from sets
of values other than ranges of consecutive integers.
A random value from the sequence 2, 5, 8, 11 ,14
int number = 2 + 3 * randomNumbers.nextInt(5);
randomNumbers.nextInt(5) produces values in the
range 0–4.
Each value produced is multiplied by 3 to produce a
number in the sequence 0, 3, 6, 9 and 12.
We add 2 to that value to shift the range of values
and obtain a value from the sequence 2, 5, 8, 11,14.
The Generalized Expression
int number = shiftingValue + differenceBetweenValues *
randomNumbers.nextInt(scalingFactor);
shiftingValue specifies the first number in the
desired range of values,
differenceBetweenValues represents the constant
difference between consecutive numbers in the
sequence
scalingFactor specifies how many numbers are in
the range.
A Game of Chance
Introducing enum Types
1.Roll two dice.
Each die has six faces, which contain one, two,
three, four, five and six spots
2. The sum of the spots on the two upward faces is
calculated.
3. If the sum is 7 or 11 on the first throw, you win.
If the sum is 2, 3 or 12 on the first throw, you lose
4. If the sum is 4, 5, 6, 8, 9 or 10 on the first throw,
that sum becomes your “point.”
4-a To win, you must continue rolling the dice until
you “make your point”
4-b You lose by rolling a 7 before making your point.
import java.security.SecureRandom;
public class Craps {
// create secure random number generator for use in method
rollDice
private static final SecureRandom randomNumbers =
new SecureRandom();
// enum type with constants that represent the game status
private enum Status { CONTINUE, WON, LOST };
// constants that represent common rolls of the dice
private static final int a = 2;
private static final int b = 3;
private static final int c = 7;
private static final int d = 11;
private static final int e = 12;
public static void main(String[] args)
{
int myPoint = 0; // point if no win or loss on first roll
Status gameStatus; // can contain CONTINUE, WON or LOST
int sumOfDice = rollDice(); // first roll of the dice
// determine game status and point based on first roll
switch (sumOfDice) {
case c: // win with 7 on first roll
case d: // win with 11 on first roll
gameStatus = Status.WON;
break;
case a: // lose with 2 on first roll
case b: / / lose with 3 on first roll
case e: // lose with 12 on first roll
gameStatus = Status.LOST; break;
default: // did not win or lose, so remember point
gameStatus = Status.CONTINUE; // game is not over
myPoint = sumOfDice; // remember the point
System.out.printf("Point is %d%n", myPoint); break;
} …………………
// while game is not complete
while (gameStatus == Status.CONTINUE)
// not WON or LOST
{
sumOfDice = rollDice(); // roll dice again
// determine game status
if (sumOfDice == myPoint) // win by making point
gameStatus = Status.WON;
else
if (sumOfDice == c
// lose by rolling 7 before point
gameStatus = Status.LOST;
}
……………………………
// display won or lost message
if (gameStatus == Status.WON)
System.out.println("Player wins");
else
System.out.println("Player loses");
}
// roll dice, calculate sum and display results
public static int rollDice()
{
// pick random die values
int die1 = 1 + randomNumbers.nextInt(6); // first die rol
int die2 = 1 + randomNumbers.nextInt(6); // second die roll
int sum = die1 + die2; // sum of die values
// display results of this roll
System.out.printf("Player rolled %d + %d = %d%n", die1, die2, sum);
return sum;
} } // end class Craps
Player rolled 5 + 6 = 11
Player wins
Player rolled 5 + 4 = 9
Point is 9
Player rolled 4 + 2 = 6
Player rolled 3 + 6 = 9
Player wins
Player rolled 1 + 2 = 3
Player loses
Player rolled 2 + 6 = 8
Point is 8
Player rolled 5 + 1 = 6
Player rolled 2 + 1 = 3
Player rolled 1 + 6 = 7
Player loses
Download