SENG2250_Assignment3/Q2Tools.java
2021-11-05 22:22:54 +11:00

76 lines
1.9 KiB
Java

import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.Random;
public class Q2Tools {
Q2Tools()
{
//Nothing to do here
}
public void generateRSA()
{
//Public Key:
BigInteger e = new BigInteger("65537");
//Generate p
SecureRandom randomNum = new SecureRandom();
BigInteger p = BigInteger.probablePrime(1024, randomNum);
//Generate q
BigInteger q = BigInteger.probablePrime(1024, randomNum);
//Generate n
BigInteger n = p.multiply(q);
//Generate phi n
BigInteger m = ((p.subtract(BigInteger.valueOf(1))).multiply((p.subtract(BigInteger.valueOf(1)))));
System.out.println("E: "+e);
System.out.println("P: "+p);
System.out.println("Q: "+q);
System.out.println("N: "+n);
System.out.println("M: "+m);
}
/**
* Performs a fast modular exponation, (base^exponent)%modulus.
* Takes input values as strings containg the numbers
* @param base
* @param exponent
* @param modulus
* @return
*/
public BigInteger fme(String base, String exponent, String modulus)
{
BigInteger baseVal = new BigInteger(base);
BigInteger exponentVal = new BigInteger(exponent);
BigInteger modulusVal = new BigInteger(modulus);
if(modulusVal.equals(BigInteger.valueOf(1)))
{
return BigInteger.valueOf(0);
}
BigInteger result = new BigInteger("1");
while(exponentVal.compareTo(BigInteger.valueOf(0))==1)
{
if(exponentVal.and(BigInteger.valueOf(1)).compareTo(BigInteger.valueOf(1))==0)
{
result = result.multiply(baseVal);
result = result.mod(modulusVal);
}
exponentVal = exponentVal.shiftRight(1);
baseVal = (baseVal.multiply(baseVal)).mod(modulusVal);
}
return result;
}
}