Assignments purpose was to use methods

Question 2 in the PDF file provided

import java.math.BigDecimal; import java.util.*; public class HussainDilawerA3Q2 { public static void main(String[] args) { long p = randomPrime(); // Generate p prime number long q = randomPrime(); // Generate q prime number long n = p*q; long phi = (p-1)*(q-1); long e = generateEKey(phi); long d = generateDKey(phi, e); [ATTACH]1901[/ATTACH] System.out.println("e: "+e+", d: "+d+"."); long enCr = encrypt(2216056, e, n); long dCr = decrypt(enCr, d, n); System.out.println(enCr); System.out.println(dCr); System.out.println(d); //this method call will give you the actall mesage after decryption long dCr1 = decrypt(2216056, 53972333, 269895149); // its message is 109 long dCr2 = decrypt(254084839, 53972333, 269895149); // its message is 101 System.out.println(dCr1); System.out.println(dCr2); } // Method to generate prime number in range 100 - 20000 public static long randomPrime(){ // Generate Random Number up to 20000 long min = 100; long max = 20000; Random rnd = new Random(); long rand = min+((long)(rnd.nextDouble()*max)); // Keep checking until the random number is prime boolean test = isPrime(rand); while (test == false){ rand = min+((long)(rnd.nextDouble()*max)); test = isPrime(rand); } // return result return rand; } // Method to check if random number is prime public static boolean isPrime(long rand) { for (int i=2; i < rand; i++){ if(rand%i == 0 && rand != i) { return false; } } return true; } public static long generateEKey(long phi){ boolean result = false; for (long e=2; e<phi; e++){ boolean test = isPrime(e); if(phi%e == 0 || test == false) { result = false; } else { return e; } }return 0; } public static long generateDKey(long phi, long e){ for(long k = 1; k < phi; k++){ long d = (k*phi+1)/e; if((d*e) % phi==1){ return d; } } return 0; } public static long encrypt(long message, long e, long n){ long result = expandedPowerMod(message, e, n); return result; } public static long decrypt(long message, long d, long n){ long result = expandedPowerMod(message, d, n); return result; } public static long expandedPowerMod(long base1,long exponent, long modulus) { long result = 0; if (base1 < 1 || exponent < 0 || modulus < 1) // just and error check for valid values return -1; result = 1; while (exponent > 0) { if ((exponent % 2) == 1) // first iteration only { result = (result * base1) % modulus; } base1 = (base1 * base1) % modulus; // multiplied and added in orignal values after taking modulus BigDecimal bd = new BigDecimal(Math.floor(exponent / 2 )); // these two steps will convert long to decimal as after division there might be some decimal values exponent = bd.setScale(0, BigDecimal.ROUND_HALF_UP).longValue(); } return result; } }