mirror of
https://github.com/zach-sb/SENG2250_Assignment3.git
synced 2025-11-09 00:57:36 +11:00
76 lines
1.9 KiB
Java
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;
|
|
}
|
|
}
|