/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package vut.msa.security;

import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.log4j.Logger;

/**
 *
 * @author starosta
 */
public class SSLContextFactory {

    private static final Logger log = Logger.getLogger(SSLContextFactory.class);

    private static SSLContext context;
    private SSLContextFactory instance;

    private final String algorithm = "SSL";
    private final String KEYSTORE = "backup.keys";
    private final String PASSWORD = "backupSERVERdemo";

    private TrustManager[] trustAllCerts = new TrustManager[]{
        new X509TrustManager() {

            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkClientTrusted(
                    java.security.cert.X509Certificate[] certs, String authType) {
            }

            public void checkServerTrusted(
                    java.security.cert.X509Certificate[] certs, String authType) {
            }
        }
    };

    private SSLContextFactory() throws Exception {
        new SSLContextFactory(algorithm, KEYSTORE, PASSWORD, trustAllCerts);
    }

    public SSLContextFactory(String algorithm,
            String keystore,
            String passphrase,
            TrustManager[] trustManager) throws Exception {

        context = SSLContext.getInstance(algorithm);
        char[] password = passphrase.toCharArray();

        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        KeyStore ks = KeyStore.getInstance("JKS");

        ks.load(new FileInputStream(keystore), password);
        kmf.init(ks, password);

        context.init(kmf.getKeyManagers(), trustAllCerts, null);
        log.info("SSLContext inicialized.");

    }

    public SSLContextFactory(String keystore) throws Exception {

        context = SSLContext.getInstance(algorithm);
        char[] password = PASSWORD.toCharArray();

        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        KeyStore ks = KeyStore.getInstance("JKS");

        ks.load(new FileInputStream(keystore), password);
        kmf.init(ks, password);

        context.init(kmf.getKeyManagers(), trustAllCerts, null);
        log.info("SSLContext inicialized.");

    }

    public static SSLContext getDefault() throws Exception {
        return new SSLContextFactory().context;
    }

    public SSLContext getContext() {
        return this.context;
    }

}
