Example usage for javax.net.ssl KeyManagerFactory getInstance

List of usage examples for javax.net.ssl KeyManagerFactory getInstance

Introduction

In this page you can find the example usage for javax.net.ssl KeyManagerFactory getInstance.

Prototype

public static final KeyManagerFactory getInstance(String algorithm) throws NoSuchAlgorithmException 

Source Link

Document

Returns a KeyManagerFactory object that acts as a factory for key managers.

Usage

From source file:ch.admin.vbs.cube.core.webservice.CubeSSLSocketFactory.java

/**
 * Create a new SSL socket factory./*from  w ww  . ja va  2  s .  com*/
 * 
 * @param keyStoreBuilder
 *            the key store builder
 * @param trustStore
 *            the trust store
 * @param checkRevocation
 *            <code>true</code> if certificate revocations should be
 *            checked, else <code>false</code>
 * @throws WebServiceException
 *             if the creation failed
 */
public static SSLSocketFactory newSSLSocketFactory(KeyStore.Builder keyStoreBuilder, KeyStore trustStore,
        boolean checkRevocation) throws WebServiceException {
    KeyManagerFactory keyManagerFactory;
    try {
        keyManagerFactory = KeyManagerFactory.getInstance("NewSunX509");
    } catch (NoSuchAlgorithmException e) {
        String message = "Unable to create key manager factory";
        LOG.error(message + ": " + e.getMessage());
        throw new WebServiceException(message, e);
    }
    KeyStoreBuilderParameters keyStoreBuilderParameters = new KeyStoreBuilderParameters(keyStoreBuilder);
    try {
        keyManagerFactory.init(keyStoreBuilderParameters);
    } catch (InvalidAlgorithmParameterException e) {
        String message = "Unable to initialize key manager factory";
        LOG.error(message + ": " + e.getMessage());
        throw new WebServiceException(message, e);
    }
    TrustManagerFactory trustManagerFactory;
    try {
        trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    } catch (NoSuchAlgorithmException e) {
        String message = "Unable to create trust manager factory";
        LOG.error(message + ": " + e.getMessage());
        throw new WebServiceException(message, e);
    }
    PKIXBuilderParameters pkixBuilderParameters;
    try {
        pkixBuilderParameters = new PKIXBuilderParameters(trustStore, null);
    } catch (KeyStoreException e) {
        String message = "The trust store is not initialized";
        LOG.error(message + ": " + e.getMessage());
        throw new WebServiceException(message, e);
    } catch (InvalidAlgorithmParameterException e) {
        String message = "The trust store does not contain any trusted certificate";
        LOG.error(message + ": " + e.getMessage());
        throw new WebServiceException(message, e);
    } catch (NullPointerException e) {
        String message = "The trust store is null";
        LOG.error(message + ": " + e.getMessage());
        throw new WebServiceException(message, e);
    }
    pkixBuilderParameters.setRevocationEnabled(checkRevocation);
    CertPathTrustManagerParameters certPathTrustManagerParameters = new CertPathTrustManagerParameters(
            pkixBuilderParameters);
    try {
        trustManagerFactory.init(certPathTrustManagerParameters);
    } catch (InvalidAlgorithmParameterException e) {
        String message = "Unable to initialize trust manager factory";
        LOG.error(message + ": " + e.getMessage());
        throw new WebServiceException(message, e);
    }
    SSLContext sslContext;
    try {
        sslContext = SSLContext.getInstance("TLS");
    } catch (NoSuchAlgorithmException e) {
        String message = "Unable to create SSL context";
        LOG.error(message + ": " + e.getMessage());
        throw new WebServiceException(message, e);
    }
    try {
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
    } catch (KeyManagementException e) {
        String message = "Unable to initialize SSL context";
        LOG.error(message + ": " + e.getMessage());
        throw new WebServiceException(message, e);
    }
    SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
    return sslSocketFactory;
}

From source file:com.mani.fileupload.http.EasySSLSocketFactory.java

private static SSLContext createEasySSLContext() throws IOException {
    try {/*from   ww  w. java 2  s  .c  o m*/

        // Client should send the valid key to Server 
        InputStream clientStream = null;
        char[] password = null;

        clientStream = FileUploadApplication.getContext().getResources().openRawResource(R.raw.client);
        password = "fileupload".toCharArray();

        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        keyStore.load(clientStream, password);

        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, password);

        // CA key obtained from server.
        KeyStore trustStore = KeyStore.getInstance("BKS");
        InputStream instream = null;
        instream = FileUploadApplication.getContext().getResources().openRawResource(R.raw.ca);

        try {
            trustStore.load(instream, "casecret".toCharArray());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                instream.close();
            } catch (Exception ignore) {
            }
        }

        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(trustStore);

        // Create an SSLContext that uses our TrustManager
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(keyManagerFactory.getKeyManagers(), tmf.getTrustManagers(), null);

        return context;
    } catch (Exception e) {
        e.printStackTrace();
        throw new IOException(e.getMessage());
    }
}

From source file:org.wso2.msf4j.conf.SSLClientContext.java

public SSLClientContext(File keyStore, String keyStorePassword) {

    try {// w  w  w  . j a  v a 2 s.co m
        KeyManagerFactory kmf = null;
        if (keyStore != null && keyStorePassword != null) {
            KeyStore ks = getKeyStore(keyStore, keyStorePassword);
            kmf = KeyManagerFactory.getInstance("SunX509");
            kmf.init(ks, keyStorePassword.toCharArray());
        }
        clientContext = SSLContext.getInstance(protocol);
        clientContext.init(kmf == null ? null : kmf.getKeyManagers(), TrustManagerFactory.getTrustManagers(),
                null);
    } catch (Exception e) {
        throw new RuntimeException("Failed to initialize the client-side SSLContext", e);
    }
}

From source file:android.apn.androidpn.server.xmpp.ssl.SSLKeyManagerFactory.java

public static KeyManager[] getKeyManagers(KeyStore keystore, String keypass) {
    KeyManager[] keyManagers;//from   ww w.ja  v  a2 s. c  om
    try {
        if (keystore == null) {
            keyManagers = null;
        } else {
            KeyManagerFactory keyFactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            if (keypass == null) {
                keypass = SSLConfig.getKeyPassword();
            }

            keyFactory.init(keystore, keypass.toCharArray());
            keyManagers = keyFactory.getKeyManagers();
        }
    } catch (KeyStoreException e) {
        keyManagers = null;
        log.error("SSLKeyManagerFactory startup problem.", e);
    } catch (NoSuchAlgorithmException e) {
        keyManagers = null;
        log.error("SSLKeyManagerFactory startup problem.", e);
    } catch (UnrecoverableKeyException e) {
        keyManagers = null;
        log.error("SSLKeyManagerFactory startup problem.", e);
    }
    return keyManagers;
}

From source file:org.wso2.carbon.identity.authenticator.PushAuthentication.java

/**
 * Set the client certificate to Default SSL Context
 *
 * @param certificateFile File containing certificate (PKCS12 format)
 * @param certPassword    Password of certificate
 * @throws Exception/*from  ww  w  .  j  av a2  s.c om*/
 */
public static SSLContext setHttpsClientCert(String certificateFile, String certPassword) throws Exception {
    if (certificateFile == null || !new File(certificateFile).exists()) {
        return null;
    }
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(InweboConstants.SUNFORMAT);
    KeyStore keyStore = KeyStore.getInstance(InweboConstants.PKCSFORMAT);

    InputStream keyInput = new FileInputStream(certificateFile);
    keyStore.load(keyInput, certPassword.toCharArray());

    keyInput.close();
    keyManagerFactory.init(keyStore, certPassword.toCharArray());

    SSLContext context = SSLContext.getInstance(InweboConstants.TLSFORMAT);
    context.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom());
    SSLContext.setDefault(context);
    return context;
}

From source file:org.apache.ftpserver.ssl.MinaClientAuthTest.java

protected FTPSClient createFTPClient() throws Exception {
    FTPSClient client = new FTPSClient(useImplicit());
    client.setNeedClientAuth(true);/*from w  w  w. ja  v  a  2 s. c  om*/

    KeyStore ks = KeyStore.getInstance("JKS");
    FileInputStream fis = new FileInputStream(FTPCLIENT_KEYSTORE);
    ks.load(fis, KEYSTORE_PASSWORD.toCharArray());
    fis.close();

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(ks, KEYSTORE_PASSWORD.toCharArray());

    client.setKeyManager(kmf.getKeyManagers()[0]);

    return client;
}

From source file:com.terradue.dsi.wire.KeyManagerProvider.java

@Override
public KeyManager[] get() {
    final char[] password = this.password.toCharArray();

    try {/*from  w w w .  j a  va2s.  c om*/
        final KeyStore store = new KeyMaterial(certificate, certificate, password).getKeyStore();
        store.load(null, password);

        // initialize key and trust managers -> default behavior
        final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
        // password for key and store have to be the same IIRC
        keyManagerFactory.init(store, password);

        return keyManagerFactory.getKeyManagers();
    } catch (Exception e) {
        throw new ProvisionException("Impossible to initialize SSL certificate/key", e);
    }
}

From source file:org.zywx.wbpalmstar.platform.certificates.HSSLSocketFactory.java

public HSSLSocketFactory(KeyStore ksP12, String keyPass) throws Exception {
    super(ksP12);
    mSSLContext = SSLContext.getInstance(SSLSocketFactory.TLS);
    KeyManagerFactory kMgrFact = null;
    TrustManager[] tMgrs = null;/*  w  ww  .  j a v  a  2 s. c om*/
    KeyManager[] kMgrs = null;
    TrustManager tMgr = null;
    tMgr = new HX509TrustManager(ksP12);
    kMgrFact = KeyManagerFactory.getInstance(Http.algorithm);
    if (null != keyPass) {
        kMgrFact.init(ksP12, keyPass.toCharArray());
    } else {
        kMgrFact.init(ksP12, null);
    }
    kMgrs = kMgrFact.getKeyManagers();
    tMgrs = new TrustManager[] { tMgr };
    SecureRandom secureRandom = new java.security.SecureRandom();
    mSSLContext.init(kMgrs, tMgrs, secureRandom);
    if (!Http.isCheckTrustCert()) {
        setHostnameVerifier(new HX509HostnameVerifier());
    } else {
        setHostnameVerifier(STRICT_HOSTNAME_VERIFIER);
    }
}

From source file:com.wudaosoft.net.httpclient.SSLContextBuilder.java

public SSLContext buildPKCS12() {

    Args.notEmpty(password, "password");
    Args.notNull(cert, "cert");

    char[] pwd = password.toCharArray();

    try {//from  ww  w  . ja  v a 2  s . c o m
        KeyStore ks = KeyStore.getInstance("PKCS12");

        ks.load(cert.openStream(), pwd);

        //  & ?
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ks, pwd);

        //  SSLContext
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(kmf.getKeyManagers(), null, new SecureRandom());

        return sslContext;
    } catch (Exception e) {
        if (e instanceof RuntimeException)
            throw (RuntimeException) e;
        throw new RuntimeException(e);
    }
}

From source file:com.fanmei.pay4j.http.WeixinSSLRequestExecutor.java

public WeixinSSLRequestExecutor(WeixinConfig weixinConfig) throws WeixinException {
    InputStream inputStream = this.getClass().getClassLoader()
            .getResourceAsStream(weixinConfig.getCertificateFile());
    try {/* ww  w  .j  a  v  a  2  s . com*/
        String password = weixinConfig.getAccount().getCertificateKey();
        KeyStore keyStore = KeyStore.getInstance(Constants.PKCS12);
        keyStore.load(inputStream, password.toCharArray());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(Constants.SunX509);
        kmf.init(keyStore, password.toCharArray());
        SSLContext sslContext = SSLContext.getInstance(Constants.TLS);
        sslContext.init(kmf.getKeyManagers(), null, new java.security.SecureRandom());

        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
        httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    } catch (Exception e) {
        throw WeixinException.of("Key load error", e);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {

            }
        }
    }
}