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

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

public class ElgamalPublicKey implements Serializable {

	private static final BigInteger TWO = BigInteger.valueOf(2);
	/**
	 * number of bits of modulus
	 */
	public int bitLength;
	/**
	 * p is a large prime.
	 */
	public BigInteger p;
	/**
	 * generator g.
	 */
	public BigInteger g;
	/**
	 * y = g^a mod p
	 */
	public BigInteger y;
	
	public ElgamalPublicKey() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * Encrypts plaintext m. 
	 * @param m plaintext as a BigInteger
	 * @return ciphertext as a CipherTextElGamal
	 */
	public CipherTextElGamal Encryption(BigInteger m) {
		SecureRandom random = new SecureRandom();
		BigInteger r = new BigInteger(bitLength, random);

		while (r.equals(BigInteger.ZERO) || (r.compareTo(p.subtract(TWO)) > 0)) {
			r = new BigInteger(bitLength, random);
		}
		return new CipherTextElGamal(m.multiply(y.modPow(r, p)).mod(p), g.modPow(r, p));
	}
	
	public boolean equals(Object arg0){
		ElgamalPublicKey pk = (ElgamalPublicKey)arg0;
		if(this.bitLength == pk.bitLength && this.p.equals(pk.p) && this.g.equals(pk.g) && this.y.equals(pk.y)) return true;
		else return false;
	}

}
