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

import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;

import com.scytl.cryptolib.api.exceptions.GeneralCryptoLibException;
import com.scytl.cryptolib.scytl.keystore.cryptoapi.CryptoAPIScytlKeyStore;
import com.scytl.products.ov.config.exceptions.ConfigurationEngineException;

public class KeyStorePersister {

	/**
     * Non-public constructor
     */
	private KeyStorePersister() {
    }
	
	public static void saveKeyStore(final CryptoAPIScytlKeyStore keyStore, final Path path,
            final char[] keyStorePassword) throws ConfigurationEngineException {

        try (final OutputStream out = Files.newOutputStream(path)) {
            keyStore.store(out, keyStorePassword);
        } catch (IOException | GeneralCryptoLibException e) {
            throw new ConfigurationEngineException(
                "An error occurred while persisting the keystore to " + path.toString(), e);
        }
    }

    public static void saveKeyStore(final KeyStore keyStore, final Path path, final char[] keyStorePassword)
            throws ConfigurationEngineException {

        try (final OutputStream out = Files.newOutputStream(path)) {
            keyStore.store(out, keyStorePassword);
        } catch (IOException | CertificateException | NoSuchAlgorithmException | KeyStoreException e) {
            throw new ConfigurationEngineException(
                "An error occurred while persisting the keystore to " + path.toString(), e);
        }
    }
}
