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

import com.scytl.cryptolib.api.exceptions.GeneralCryptoLibException;
import com.scytl.cryptolib.api.stores.bean.KeyStoreType;
import com.scytl.cryptolib.stores.service.StoresService;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;

public class TestKeyStoreGenerator {

  /**
   * Creates a PKCS12 keystore for a certificate chain.
   *
   * @param privateKey the private key to store in the key store
   * @param keyAlias the alias of such private key
   * @param password the key store password
   * @param certificateChain the certificate chain for the private key
   * @return a key store
   */
  public static KeyStore createKeystore(PrivateKey privateKey, String keyAlias, char[] password,
      X509Certificate[] certificateChain) {
    if (certificateChain.length < 1) {
      throw new IllegalArgumentException(
          "The certificate chain must contain at least one certificate");
    }

    KeyStore keyStore;
    try {
      StoresService storesService = new StoresService();
      keyStore = storesService.createKeyStore(KeyStoreType.PKCS12);
    } catch (GeneralCryptoLibException e) {
      throw new RuntimeException("An error occurred while preparing the PKCS12 key store", e);
    }

    try {
      keyStore.setKeyEntry(keyAlias, privateKey, password, certificateChain);
    } catch (KeyStoreException e) {
      throw new RuntimeException("An error occurred while preparing the PKCS12 key store", e);
    }

    return keyStore;
  }
}
