package lc.mecha.security;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;

/**
 * @author Alex leigh
 * @since mk20 (TOKYO PROTOCOL)
 */
public class KeyStoreUtil {
    private final static char[] DUMMY_PASSWORD = "a".toCharArray();

    /**
     * Create a full deep clone of the provided {@link KeyStore} and return it to the caller.
     *
     * @param keyStore The KeyStore to clone.
     * @return The cloned KeyStore.
     * @throws CertificateException
     * @throws KeyStoreException
     * @throws IOException
     * @throws NoSuchAlgorithmException
     */
    public static KeyStore cloneKeyStore(KeyStore keyStore) throws CertificateException, KeyStoreException, IOException,
            NoSuchAlgorithmException {
        var bo = new ByteArrayOutputStream();
        keyStore.store(bo, DUMMY_PASSWORD);
        bo.close();

        var bi = new ByteArrayInputStream(bo.toByteArray());
        var cloneStore = KeyStore.getInstance(KeyStore.getDefaultType());
        cloneStore.load(bi, DUMMY_PASSWORD);

        return cloneStore;
    }
}
