300 likes | 529 Views
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.
E N D
A Java API Packagejava.security The Java Security Packagecontainsclassesandinterfacesthatarerequiredbymany Java programs. Thispackage is importedbycompilerintoallprograms 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 SecureRandomextends Random • Randomclass is in java.utility • This class provides a cryptographically strong random number generator (RNG).
Moving to Secure Random NumbersfromRandomNumbers • Java’sRandom classis 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 possibleto use class Random from package java.util • It is requiredsimply toreplace SecureRandom with Random.
Creating a SecureRandom Object A new secure random-number generator object can be created as SecureRandomrandomNumbers= newSecureRandom(); • It can then be used to generate random • For more information on the SecureRandomclass docs.oracle.com/javase/7/docs/api/java/security/SecureRandom.html
Obtaining a Random int Value Consider the following statement intrandomValue = randomNumbers.nextInt(); SecureRandommethod nextIntgenerates a random intvalue. 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 • Themethod nextIntgenerally differs from the range of values required in anyJava application. • Aprogram that simulates coin tossing might require only 0 for “heads” and 1 for “tails.” • A program that simulates the rolling of a six-sided die might require random integers in the range 1–6.
Changing the Range of Values Produced By nextInt • classSecureRandom provides another version of method nextIntthat 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. intrandomValue = randomNumbers.nextInt(2);
Rolling a Six-Sided Die • Theprogram simulates 20 rolls of a six-sided die and displays the value of each roll. • nextInt produces random values in the range 0–5 intface = randomNumbers.nextInt(6); • The argument 6 is scaling factor • the number of values that nextIntshould 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. • shiftthe range of numbers produced by adding a shifting value intface = 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 SecureRandomrandomNumbers= newSecureRandom(); // loop 20 times for (int counter = 1; counter <= 20; counter++) {// pick random integer from 1 to 6 intface = 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 ScaledRandomIntegers. 1 5 3 6 25 2 6 5 24 4 4 2 63 1 6 2 2 6 5 4 2 61 2 5 1 36 3 2 2 16 4 2 6 4
Rolling a Six-Sided Die 6,000,000 Times importjava.security.SecureRandom; public class RollDie {public static void main(String[] args) { // randomNumbers object will produce secure random numbers SecureRandomrandomNumbers= new SecureRandom(); intfrequency1 = 0; // count of 1s rolled intfrequency2 = 0; // count of 2s rolled intfrequency3 = 0; // count of 3s rolled int frequency4 = 0; // count of 4s rolled intfrequency5 = 0; // count of 5s rolled intfrequency6 = 0; // count of 6s rolled // tally counts for 6,000,000 rolls of a die
…… for (introll = 1; roll <= 6000000; roll++) { intface = 1 + randomNumbers.nextInt(6); ……….; // number from 1 to 6 switch(face) { case1: ……; • Scalingand 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 counterbreak; case 3: ++frequency3; // increment the 3s counter break; case 4: ++frequency4; // increment the 4s counterbreak; case 5: ++frequency5; // increment the 5s counter break; case 6: ++frequency6; // increment the 6s counterbreak;}
NestedControlStatementsfor & switchcase • Theswitch is nested inside theforto determine the number of times each side of the die appears. • The for statement iterates 6,000,000 times. • During each iterationproduces 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. • Theswitch 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.
……. } //endforstatement 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 Frequency1 9995012 10004123 9982624 10008205 10022456 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 simulatedwith the statement intface = 1 + randomNumbers.nextInt(6); • This statement always assigns to variable face an integer in the range1 ≤ face ≤ 6. • The width of the range is determined by the number 6 • Thisnumber is passed as an argument to SecureRandommethodnextInt • 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); • shiftingValuespecifies the first number in the desired range of consecutive integers • scalingFactorspecifies 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. • Arandom value from the sequence 2, 5, 8, 11 ,14 intnumber = 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.
TheGeneralizedExpression int number = shiftingValue+ differenceBetweenValues* randomNumbers.nextInt(scalingFactor); • shiftingValuespecifies the first number in the desired range of values, • differenceBetweenValuesrepresents the constant difference between consecutive numbers in the sequence • scalingFactorspecifies how many numbers are in the range.
A Game of ChanceIntroducing enum Types 1.Rolltwo 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.
importjava.security.SecureRandom; public classCraps { // create secure random number generator for use in method rollDice private static final SecureRandomrandomNumbers= 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 inta= 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){ intmyPoint = 0; // point if no win or loss on first roll Status gameStatus; // can contain CONTINUE, WON or LOST intsumOfDice = rollDice(); // first roll of the dice // determine game status and point based on first roll switch (sumOfDice){ casec: // 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 introllDice() { // pick random die values intdie1 = 1 + randomNumbers.nextInt(6); // first die rol intdie2 = 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 1 + 2 = 3 Player loses 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 2 + 6 = 8 Point is 8 Player rolled 5 + 1 = 6 Player rolled 2 + 1 = 3 Player rolled 1 + 6 = 7 Player loses