package com.jscape.inet.ssh.util.keyreader;

import com.jscape.util.io.ByteArrayInputStream;
import com.jscape.util.keystore.KeyStoreCodec;

import java.security.*;
import java.security.cert.Certificate;
import java.util.Enumeration;

import static com.jscape.util.Parameters.assertNotNull;

/**
 * @author Alex Uzun
 */
public class KeyStoreKeyPairFormat
        implements KeyPairFormat {

    private final String type;
    private final Provider provider;

    public KeyStoreKeyPairFormat(String type, Provider provider) {
        assertNotNull(type);
        this.type = type;

        this.provider = provider;
    }

    @Override
    public KeyPair restoreKeyPair(byte[] data, String passphrase)
            throws FormatException {
        try {
            KeyStore store = KeyStoreCodec.readValue(new ByteArrayInputStream(data), this.type, passphrase, this.provider);
            String alias = firstKeyAliasIn(store);
            PrivateKey privateKey = (PrivateKey) store.getKey(alias, passphrase.toCharArray());
            Certificate[] certificates = store.getCertificateChain(alias);
            PublicKey publicKey = certificates[0].getPublicKey();

            return new KeyPair(publicKey, privateKey);
        } catch (Exception e) {
            throw new FormatException(e);
        }
    }

    private String firstKeyAliasIn(KeyStore store)
            throws Exception {
        for (Enumeration<String> e = store.aliases(); e.hasMoreElements(); ) {
            String candidate = e.nextElement();
            if (store.isKeyEntry(candidate)) {
                return candidate;
            }
        }

        return "";
    }
}
