package gr.duth.eece.cryptographyLesson.asymmetric.rsa;

import java.io.Serializable;
import java.math.BigInteger;
import java.security.SecureRandom;

public class RSAKeyPair implements Serializable{

	public RSAPublicKey PublicKey;
	public RSAPrivateKey PrivateKey;

	public RSAKeyPair(int bitLengthVal) {
		// TODO Auto-generated constructor stub
		KeyGeneration(bitLengthVal, 100);
	}

	private void KeyGeneration(int bitLengthVal, int certainty) {
		int bitLength = bitLengthVal;
		/*Constructs two randomly generated positive BigIntegers that are probably prime, with the specified bitLength and certainty.*/
	    SecureRandom r = new SecureRandom();
	    BigInteger p = new BigInteger(bitLength / 2, 100, r);
	    BigInteger q = new BigInteger(bitLength / 2, 100, r);
	    BigInteger n = p.multiply(q);
	    BigInteger phi = (p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE));
	    
	    BigInteger e = BigInteger.probablePrime(bitLength / 2, r);
        while (phi.gcd(e).compareTo(BigInteger.ONE) > 0 && e.compareTo(phi) < 0)
        {
            e.add(BigInteger.ONE);
        }
        BigInteger d = e.modInverse(phi);
	    
		PublicKey = new RSAPublicKey();
		PublicKey.bitLength = bitLength;
		PublicKey.n = n;
		PublicKey.e = e;

		PrivateKey = new RSAPrivateKey();
		PrivateKey.bitLength = bitLength;
		PrivateKey.n = n;
		PrivateKey.d = d;
	}

}
