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:org.apache.geode.internal.net.SocketCreator.java

private KeyManager[] getKeyManagers() throws KeyStoreException, IOException, NoSuchAlgorithmException,
        CertificateException, UnrecoverableKeyException {
    GfeConsoleReader consoleReader = GfeConsoleReaderFactory.getDefaultConsoleReader();

    KeyManager[] keyManagers = null;
    String keyStoreType = sslConfig.getKeystoreType();
    if (StringUtils.isEmpty(keyStoreType)) {
        // read from console, default on empty
        if (consoleReader.isSupported()) {
            keyStoreType = consoleReader
                    .readLine("Please enter the keyStoreType (javax.net.ssl.keyStoreType) : ");
        } else {//from  w ww  .j  a  v  a 2s  . c  om
            keyStoreType = KeyStore.getDefaultType();
        }
    }
    KeyStore keyStore = KeyStore.getInstance(keyStoreType);
    String keyStoreFilePath = sslConfig.getKeystore();
    if (StringUtils.isEmpty(keyStoreFilePath)) {
        if (consoleReader.isSupported()) {
            keyStoreFilePath = consoleReader
                    .readLine("Please enter the keyStore location (javax.net.ssl.keyStore) : ");
        } else {
            keyStoreFilePath = System.getProperty("user.home") + System.getProperty("file.separator")
                    + ".keystore";
        }
    }

    FileInputStream fileInputStream = new FileInputStream(keyStoreFilePath);
    String passwordString = sslConfig.getKeystorePassword();
    char[] password = null;
    if (passwordString != null) {
        if (passwordString.trim().equals("")) {
            String encryptedPass = System.getenv("javax.net.ssl.keyStorePassword");
            if (!StringUtils.isEmpty(encryptedPass)) {
                String toDecrypt = "encrypted(" + encryptedPass + ")";
                passwordString = PasswordUtil.decrypt(toDecrypt);
                password = passwordString.toCharArray();
            }
            // read from the console
            if (StringUtils.isEmpty(passwordString) && consoleReader != null) {
                password = consoleReader
                        .readPassword("Please enter password for keyStore (javax.net.ssl.keyStorePassword) : ");
            }
        } else {
            password = passwordString.toCharArray();
        }
    }
    keyStore.load(fileInputStream, password);
    // default algorithm can be changed by setting property "ssl.KeyManagerFactory.algorithm" in
    // security properties
    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, password);
    keyManagers = keyManagerFactory.getKeyManagers();
    // follow the security tip in java doc
    if (password != null) {
        java.util.Arrays.fill(password, ' ');
    }

    KeyManager[] extendedKeyManagers = new KeyManager[keyManagers.length];

    for (int i = 0; i < keyManagers.length; i++)

    {
        extendedKeyManagers[i] = new ExtendedAliasKeyManager(keyManagers[i], sslConfig.getAlias());
    }

    return extendedKeyManagers;
}

From source file:org.ejbca.core.protocol.ws.CommonEjbcaWS.java

/** Getting SSL socket factory using the Admin cert created for client certificate authentication **/
private SSLSocketFactory getSSLFactory() throws IOException, NoSuchAlgorithmException,
        UnrecoverableKeyException, KeyStoreException, CertificateException, KeyManagementException {
    // Put the key and certs in the user keystore (if available)
    java.security.KeyStore ks = java.security.KeyStore.getInstance("jks");
    ks.load(new FileInputStream(TEST_ADMIN_FILE), PASSWORD.toCharArray());
    final KeyManagerFactory kmf;
    kmf = KeyManagerFactory.getInstance("SunX509");
    kmf.init(ks, PASSWORD.toCharArray());
    final KeyManager km[] = kmf.getKeyManagers();

    final TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
    tmf.init(ks);//from www  .j  av  a  2 s  .c  o  m
    final TrustManager tm[] = tmf.getTrustManagers();
    if (km == null && tm == null) {
        return (SSLSocketFactory) SSLSocketFactory.getDefault();
    }
    final SSLContext ctx = SSLContext.getInstance("TLS");
    ctx.init(km, tm, null);
    return ctx.getSocketFactory();
}

From source file:edu.washington.shibboleth.attribute.resolver.provider.dataConnector.RwsDataConnector.java

/**
 * This sets the key managers that will be used for all TLS and SSL connections to the ldap. 
 * //  w  w w  .  ja  va2 s .  c o  m
 * @see #clearCache()
 * @see #initializeHttpPool()
 * @see #setSslSocketFactory(SSLSocketFactory)
 * 
 * @param kc <code>X509Credential</code> to create KeyManagers with
 */
public void setSslKeyManagers(X509Credential kc) {
    if (kc != null) {
        try {
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
            keystore.load(null, null);
            keystore.setKeyEntry("ldap_tls_client_auth", kc.getPrivateKey(), "changeit".toCharArray(),
                    kc.getEntityCertificateChain().toArray(new X509Certificate[0]));
            kmf.init(keystore, "changeit".toCharArray());
            sslKeyManagers = kmf.getKeyManagers();
        } catch (GeneralSecurityException e) {
            log.error("Error initializing key managers", e);
        } catch (IOException e) {
            log.error("Error initializing key managers", e);
        }
    }
}

From source file:com.sat.vcse.automation.utils.http.HttpClient.java

private SSLContext getSSLContext() {

    final String METHOD_NAME = "getSSLContext(): ";
    SSLContext sslContext = null;

    try {/*from  w  w  w.ja  va  2  s. c o m*/
        //Get the TrustManager based on client truststore file presence or no
        final TrustManager[] trustManager = getTrustManagers();
        // Configure the SSLContext object with the defined cryptoProtocol 
        sslContext = SSLContext.getInstance(this.cryptoProtocol);

        if (this.isClientAuthEnabled) {
            // Load the Client Keystore
            final KeyManagerFactory kmf = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            final KeyStore clientKeystore = KeyStore.getInstance(KeyStore.getDefaultType());

            InputStream keystoreis = null;
            //see if the file is present otherwise read from class path
            File keStoreFile = new File(this.keystore);
            if (keStoreFile.exists()) {
                keystoreis = new FileInputStream(keStoreFile);
            } else {
                LogHandler.warn("File not found, so trying to read it from class path now");
                keystoreis = HttpClient.class.getResourceAsStream(this.keystore);
            }

            clientKeystore.load(keystoreis, this.keystorePasswd.toCharArray());
            kmf.init(clientKeystore, this.keystorePasswd.toCharArray());
            // Configure the SSLContext object with the Keystore, Truststore and random data 
            sslContext.init(kmf.getKeyManagers(), trustManager, new SecureRandom());

        } else {
            // Configure the SSLContext object with the only a Truststore and random data 
            sslContext.init(null, trustManager, new SecureRandom());
        }

    } catch (Exception exp) {
        LogHandler.error(CLASS_NAME + METHOD_NAME + exp.getMessage());
        throw new CoreRuntimeException(exp, CLASS_NAME + METHOD_NAME + exp.getMessage());
    }

    return sslContext;
}

From source file:org.wso2.extension.siddhi.store.mongodb.util.MongoTableUtils.java

private static SocketFactory extractSocketFactory(String trustStore, String trustStorePassword, String keyStore,
        String keyStorePassword) {
    TrustManager[] trustManagers;
    KeyManager[] keyManagers;/*from   w ww .  j av a 2 s .c o m*/

    try (InputStream trustStream = new FileInputStream(trustStore)) {
        char[] trustStorePass = trustStorePassword.toCharArray();
        KeyStore trustStoreJKS = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStoreJKS.load(trustStream, trustStorePass);
        TrustManagerFactory trustFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustFactory.init(trustStoreJKS);
        trustManagers = trustFactory.getTrustManagers();
    } catch (FileNotFoundException e) {
        throw new MongoTableException("Trust store file not found for secure connections to mongodb. "
                + "Trust Store file path : '" + trustStore + "'.", e);
    } catch (IOException e) {
        throw new MongoTableException(
                "I/O Exception in creating trust store for secure connections to mongodb. "
                        + "Trust Store file path : '" + trustStore + "'.",
                e);
    } catch (CertificateException e) {
        throw new MongoTableException("Certificates in the trust store could not be loaded for secure "
                + "connections to mongodb. Trust Store file path : '" + trustStore + "'.", e);
    } catch (NoSuchAlgorithmException e) {
        throw new MongoTableException("The algorithm used to check the integrity of the trust store cannot be "
                + "found. Trust Store file path : '" + trustStore + "'.", e);
    } catch (KeyStoreException e) {
        throw new MongoTableException("Exception in creating trust store, no Provider supports aKeyStoreSpi "
                + "implementation for the specified type. Trust Store file path : '" + trustStore + "'.", e);
    }

    try (InputStream keyStream = new FileInputStream(keyStore)) {
        char[] keyStorePass = keyStorePassword.toCharArray();
        KeyStore keyStoreJKS = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStoreJKS.load(keyStream, keyStorePass);
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStoreJKS, keyStorePass);
        keyManagers = keyManagerFactory.getKeyManagers();
    } catch (FileNotFoundException e) {
        throw new MongoTableException("Key store file not found for secure connections to mongodb. "
                + "Key Store file path : '" + keyStore + "'.", e);
    } catch (IOException e) {
        throw new MongoTableException(
                "I/O Exception in creating trust store for secure connections to mongodb. "
                        + "Key Store file path : '" + keyStore + "'.",
                e);
    } catch (CertificateException e) {
        throw new MongoTableException("Certificates in the trust store could not be loaded for secure "
                + "connections to mongodb. Key Store file path : '" + keyStore + "'.", e);
    } catch (NoSuchAlgorithmException e) {
        throw new MongoTableException("The algorithm used to check the integrity of the trust store cannot be "
                + "found. Key Store file path : '" + keyStore + "'.", e);
    } catch (KeyStoreException e) {
        throw new MongoTableException(
                "Exception in creating trust store, no Provider supports aKeyStoreSpi "
                        + "implementation for the specified type. Key Store file path : '" + keyStore + "'.",
                e);
    } catch (UnrecoverableKeyException e) {
        throw new MongoTableException(
                "Key in the keystore cannot be recovered. " + "Key Store file path : '" + keyStore + "'.", e);
    }

    try {
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(keyManagers, trustManagers, null);
        SSLContext.setDefault(sslContext);
        return sslContext.getSocketFactory();
    } catch (KeyManagementException e) {
        throw new MongoTableException(
                "Error in validating the key in the key store/ trust store. " + "Trust Store file path : '"
                        + trustStore + "'. " + "Key Store file path : '" + keyStore + "'.",
                e);
    } catch (NoSuchAlgorithmException e) {
        throw new MongoTableException(
                " SSL Algorithm used to create SSL Socket Factory for mongodb connections " + "is not found.",
                e);
    }

}

From source file:org.wildfly.security.sasl.entity.EntityTest.java

private X509KeyManager getX509KeyManager(final File keyStore, final char[] keyStorePassword)
        throws GeneralSecurityException, IOException {
    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(loadKeyStore(keyStore), keyStorePassword);
    for (KeyManager keyManager : keyManagerFactory.getKeyManagers()) {
        if (keyManager instanceof X509KeyManager) {
            return (X509KeyManager) keyManager;
        }//from   w ww .  j a v a2 s .  c om
    }
    return null;
}

From source file:org.jivesoftware.smack.XMPPConnection.java

/**
 * The server has indicated that TLS negotiation can start. We now need to secure the
 * existing plain connection and perform a handshake. This method won't return until the
 * connection has finished the handshake or an error occured while securing the connection.
 *
 * @throws Exception if an exception occurs.
 */// w ww. j av  a  2s  .c o m
void proceedTLSReceived() throws Exception {
    SSLContext context = SSLContext.getInstance("TLS");
    KeyStore ks = null;
    KeyManager[] kms = null;
    PasswordCallback pcb = null;

    if (config.getCallbackHandler() == null) {
        ks = null;
    } else {
        //System.out.println("Keystore type: "+configuration.getKeystoreType());
        if (config.getKeystoreType().equals("NONE")) {
            ks = null;
            pcb = null;
        } else if (config.getKeystoreType().equals("PKCS11")) {
            try {
                Constructor c = Class.forName("sun.security.pkcs11.SunPKCS11")
                        .getConstructor(InputStream.class);
                String pkcs11Config = "name = SmartCard\nlibrary = " + config.getPKCS11Library();
                ByteArrayInputStream config = new ByteArrayInputStream(pkcs11Config.getBytes());
                Provider p = (Provider) c.newInstance(config);
                Security.addProvider(p);
                ks = KeyStore.getInstance("PKCS11", p);
                pcb = new PasswordCallback("PKCS11 Password: ", false);
                this.config.getCallbackHandler().handle(new Callback[] { pcb });
                ks.load(null, pcb.getPassword());
            } catch (Exception e) {
                ks = null;
                pcb = null;
            }
        } else if (config.getKeystoreType().equals("Apple")) {
            ks = KeyStore.getInstance("KeychainStore", "Apple");
            ks.load(null, null);
            //pcb = new PasswordCallback("Apple Keychain",false);
            //pcb.setPassword(null);
        } else {
            ks = KeyStore.getInstance(config.getKeystoreType());
            try {
                pcb = new PasswordCallback("Keystore Password: ", false);
                config.getCallbackHandler().handle(new Callback[] { pcb });
                ks.load(new FileInputStream(config.getKeystorePath()), pcb.getPassword());
            } catch (Exception e) {
                ks = null;
                pcb = null;
            }
        }
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        try {
            if (pcb == null) {
                kmf.init(ks, null);
            } else {
                kmf.init(ks, pcb.getPassword());
                pcb.clearPassword();
            }
            kms = kmf.getKeyManagers();
        } catch (NullPointerException npe) {
            kms = null;
        }
    }

    // Verify certificate presented by the server
    context.init(kms, new javax.net.ssl.TrustManager[] { new ServerTrustManager(getServiceName(), config) },
            new java.security.SecureRandom());
    Socket plain = socket;
    // Secure the plain connection
    socket = context.getSocketFactory().createSocket(plain, plain.getInetAddress().getHostName(),
            plain.getPort(), true);
    socket.setSoTimeout(0);
    socket.setKeepAlive(true);
    // Initialize the reader and writer with the new secured version
    initReaderAndWriter();
    // Proceed to do the handshake
    ((SSLSocket) socket).startHandshake();
    //if (((SSLSocket) socket).getWantClientAuth()) {
    //    System.err.println("Connection wants client auth");
    //}
    //else if (((SSLSocket) socket).getNeedClientAuth()) {
    //    System.err.println("Connection needs client auth");
    //}
    //else {
    //    System.err.println("Connection does not require client auth");
    // }
    // Set that TLS was successful
    usingTLS = true;

    // Set the new  writer to use
    packetWriter.setWriter(writer);
    // Send a new opening stream to the server
    packetWriter.openStream();
}

From source file:org.deviceconnect.android.message.DevicePluginContext.java

/**
 * SSLContext ?????./*from ww  w .  ja  v a 2 s .  c  o  m*/
 * <p>
 * ? Web ?????Manager???????????SSLContext ???
 * </p>
 * @param keyStore 
 * @return SSLContext?
 * @throws GeneralSecurityException SSLContext???????
 */
protected SSLContext createSSLContext(final KeyStore keyStore) throws GeneralSecurityException {
    SSLContext sslContext = SSLContext.getInstance("TLS");
    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, "0000".toCharArray());
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(keyStore);
    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
            new SecureRandom());
    return sslContext;
}

From source file:android.core.SSLSocketTest.java

/**
 * Loads a keystore from a base64-encoded String. Returns the KeyManager[]
 * for the result./*from   w  ww  . j av a  2s.  c  o m*/
 */
private KeyManager[] getKeyManagers(String keys) throws Exception {
    byte[] bytes = new Base64().decode(keys.getBytes());
    InputStream inputStream = new ByteArrayInputStream(bytes);

    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(inputStream, PASSWORD.toCharArray());
    inputStream.close();

    String algorithm = KeyManagerFactory.getDefaultAlgorithm();
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(algorithm);
    keyManagerFactory.init(keyStore, PASSWORD.toCharArray());

    return keyManagerFactory.getKeyManagers();
}