/*
 * 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.config.shares.keys.elgamal;

import java.security.KeyException;
import java.security.KeyPair;

import com.scytl.cryptolib.api.elgamal.ElGamalServiceAPI;
import com.scytl.cryptolib.api.exceptions.GeneralCryptoLibException;
import com.scytl.cryptolib.elgamal.bean.ElGamalEncryptionParameters;
import com.scytl.cryptolib.elgamal.bean.ElGamalKeyPair;
import com.scytl.products.ov.config.shares.keys.KeyPairGenerator;

public final class ElGamalKeyPairGenerator implements KeyPairGenerator {

    private final ElGamalServiceAPI elGamalServiceAPI;

    private final ElGamalEncryptionParameters encryptionParameters;

    private final int subkeyCount;

    public ElGamalKeyPairGenerator(final ElGamalEncryptionParameters encyptionParameters, int subkeyCount,
            ElGamalServiceAPI elGamalServiceAPI) {
        this.encryptionParameters = encyptionParameters;
        this.subkeyCount = subkeyCount;
        this.elGamalServiceAPI = elGamalServiceAPI;
    }

    @Override
    public KeyPair generate() throws KeyException {

        ElGamalKeyPair generatedKeyPair;
        try {
            generatedKeyPair = elGamalServiceAPI.getElGamalKeyPairGenerator().generateKeys(encryptionParameters,
                subkeyCount);
        } catch (GeneralCryptoLibException e) {
            throw new KeyException("An error occurred while generating the ElGamal key pair", e);
        }
        return new KeyPair(new ElGamalPublicKeyAdapter(generatedKeyPair.getPublicKeys()),
            new ElGamalPrivateKeyAdapter(generatedKeyPair.getPrivateKeys()));
    }
}
