/*
 * Copyright 2018 Scytl Secure Electronic Voting SA
 *
 * All rights reserved
 *
 * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
 */
package com.scytl.products.ov.encryption.params.generation;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import java.math.BigInteger;
import java.security.Security;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.BeforeClass;
import org.junit.Test;

import com.scytl.cryptolib.api.exceptions.GeneralCryptoLibException;
import com.scytl.cryptolib.elgamal.bean.ElGamalEncryptionParameters;
import com.scytl.cryptolib.primitives.service.PrimitivesService;

public class UniversalElGamalEncryptionParametersGeneratorTest {

    private static UniversalElGamalEncryptionParamsGenerator _target;

    @BeforeClass
    public static void setUp() throws GeneralCryptoLibException {

        Security.addProvider(new BouncyCastleProvider());

        _target = new UniversalElGamalEncryptionParamsGenerator(new PrimitivesService());
    }

    @Test
    public void generate_ZpSubGroup_encryption_parameters() {

        int pLength = 1024;
        int qLength = 160;

        ElGamalEncryptionParameters elGamalEncryptionParameters =
            _target.generateZpSubGroupEncryptionParameters(pLength, qLength);

        String errorMsg = "P does not have the expected length. Expected: " + pLength + ", but was: "
            + elGamalEncryptionParameters.getP().bitLength();
        assertEquals(errorMsg, pLength, elGamalEncryptionParameters.getP().bitLength());

        errorMsg = "Q does not have the expected length. Expected: " + qLength + ", but was: "
            + elGamalEncryptionParameters.getQ().bitLength();
        assertEquals(errorMsg, qLength, elGamalEncryptionParameters.getQ().bitLength());
    }

    @Test
    public void generate_quadratic_residue_encryption_parameters() throws GeneralCryptoLibException {

        int lengthOfP = 10;

        ElGamalEncryptionParameters elGamalEncryptionParameters =
            _target.generateQuadraticResidueEncryptionParameters(lengthOfP);

        String errorMsg = "The returned p parameter was not the expected value";
        assertEquals(errorMsg, lengthOfP, elGamalEncryptionParameters.getP().bitLength());

        BigInteger p = elGamalEncryptionParameters.getP();
        BigInteger q = elGamalEncryptionParameters.getQ();

        BigInteger expectedP = q.multiply(new BigInteger("2")).add(BigInteger.ONE);

        errorMsg = "P and Q do not have the expected relationship, P: " + p + ", Q: " + q;
        assertTrue(errorMsg, p.equals(expectedP));
    }
}
