/*
 * 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.service;

import java.security.KeyException;
import java.security.PrivateKey;
import java.util.ArrayList;
import java.util.List;

import com.scytl.products.ov.config.shares.keys.PrivateKeySerializer;
import com.scytl.shares.ShamirAlgorithm;
import com.scytl.shares.Share;
import com.scytl.shares.ShareException;

public final class PrivateKeySharesService {

    private final PrivateKeySerializer privateKeySerializer;

    private final ShamirAlgorithm sa;

    public PrivateKeySharesService(final PrivateKeySerializer privateKeySerializer) {
        this.privateKeySerializer = privateKeySerializer;
        this.sa = new ShamirAlgorithm();
    }

    public List<Share> split(final PrivateKey privateKey, final int n, final int threshold) throws KeyException {

        byte[] secretForShamir = privateKeySerializer.serialize(privateKey);

        try {
            return new ArrayList<Share>(sa.split(secretForShamir, n, threshold));
        } catch (ShareException e) {
            throw new KeyException("An error occurred while trying to split the private key", e);
        }
    }
}
