when running the following code it runs one time correctly and after that when I try to run it again, it fails.
Any Help. I'm using jGRASP editor
Thanks
import java.util.*; import java.math.*; public class DiffieHellmanBigInt { public static void main(String args[]) { int p; System.out.println("Enter the number of bits to compute the value of the Prime Number:"); Scanner userInput = new Scanner(System.in); int ans = Integer.parseInt(userInput.next()); p = getPrime(ans); System.out.println("The value of p selected:"+ p); //Random numbers Generation Random rand=new Random(); int g = rand.nextInt((p - 2) + 1) + 2; //between 2 and (p-1) System.out.println("The value of g selected: "+ g); int a = rand.nextInt(99); //generating value of a System.out.println("The value of a selected by Alice: "+ a); int b = rand.nextInt(99);//generating value of b System.out.println("The value of b selected by Bob: "+ b); // A's calculation. int comput_A=(int)Math.pow(g, a)%p; System.out.println("The value of A sent to Bob by Alice: "+ comput_A); // B's calculation. int comput_B = (int)Math.pow(g, b)%p; System.out.println("The value of B sent to Alice by Bob: "+ comput_B); int KeyA = (int) Math.pow(comput_B, a)%p; int KeyB = (int)Math.pow(comput_A, b)%p; if(KeyA==KeyB) { System.out.println("The value of key shared between Alice and Bob: "+ KeyA); } else { System.out.println("There is an Error"); // System.out.println("The Key A calculates is "+KeyA); //System.out.println("The Key B calculates is "+KeyB); } } // evaluate if a number is prime or not public static boolean isPrime(int n) { for(int i=2;i<n;i++) { if(n%i==0) { return false; } } return true; } // find a prime number public static int getPrime(int ans) { boolean foundPrime= false; Random rand_pr = new Random(); if(!foundPrime) { int num1 = (int)Math.pow(2, ans-1); int num2 = (int)Math.pow(2, ans); int pr = rand_pr.nextInt(num2 - num1 + 1) + num1; if (isPrime(pr)) { return pr; } } return 0; } }
Output 1:
Enter the number of bits to compute the value of the Prime Number:
5
The value of p selected:19
The value of g selected: 3
The value of a selected by Alice: 57
The value of b selected by Bob: 88
The value of A sent to Bob by Alice: 2
The value of B sent to Alice by Bob: 2
The value of key shared between Alice and Bob: 2
Output 2:
Enter the number of bits to compute the value of the Prime Number:
5
The value of p selected:0
Exception in thread "main" java.lang.IllegalArgumentException: bound must be positive
at java.util.Random.nextInt(Random.java:388)
at DiffieHellmanBigInt.main(DiffieHellmanBigInt.java: 24)
----jGRASP wedge2: exit code for process is 1.