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

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.KeyStore;

import com.scytl.cryptolib.api.exceptions.GeneralCryptoLibException;
import com.scytl.cryptolib.scytl.keystore.cryptoapi.CryptoAPIScytlKeyStore;
import com.scytl.cryptolib.scytl.keystore.service.ScytlKeyStoreService;
import com.scytl.products.ov.commons.beans.exceptions.CryptoException;

/**
 * Provides utilities for handling Scytl keystores.
 */
public class KeyStoreLoader {

	/**
	 * Non-public constructor
	 */
	private KeyStoreLoader() {
		
	}
	
    /**
     * Load keystore from the specified path, using the specified password.
     */
    public static CryptoAPIScytlKeyStore loadPlatformRootKeyStore(final Path keystorePath, final char[] password)
            throws CryptoException {

        try {
            return loadKeyStoreFromStream(Files.newInputStream(keystorePath), password);
        } catch (IOException e) {
            throw new CryptoException("Failed to load keystore. Error was: " + e.getMessage(), e);
        }
    }

    /**
     * Load keystore from the specified inputstream, using the specified password.
     */
    public static CryptoAPIScytlKeyStore loadKeyStoreFromStream(final InputStream in, final char[] password)
            throws CryptoException {

        KeyStore.PasswordProtection passwordProtection = new KeyStore.PasswordProtection(password);
        CryptoAPIScytlKeyStore cryptoScytlKeyStore = null;
        try {
            ScytlKeyStoreService scytlKeyStoreService = new ScytlKeyStoreService();
            cryptoScytlKeyStore = scytlKeyStoreService.loadKeyStore(in, passwordProtection);
        } catch (GeneralCryptoLibException e) {
            throw new CryptoException("The keystore cannot be opened with the given password", e);
        }
        return cryptoScytlKeyStore;
    }
}
