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.wso2.carbon.esb.rabbitmq.message.store.jira.ESBJAVA4569RabbiMQSSLStoreWithClientCertValidationTest.java

/**
 * Helper method to retrieve queue message from rabbitMQ
 *
 * @return result/* ww  w  .  jav  a2 s. co  m*/
 * @throws Exception
 */
private static String consumeWithoutCertificate() throws Exception {
    String result = "";

    String basePath = TestConfigurationProvider.getResourceLocation()
            + "/artifacts/ESB/messageStore/rabbitMQ/SSL/";

    String truststoreLocation = basePath + "rabbitMQ/certs/client/rabbitstore";
    String keystoreLocation = basePath + "rabbitMQ/certs/client/keycert.p12";

    char[] keyPassphrase = "MySecretPassword".toCharArray();
    KeyStore ks = KeyStore.getInstance("PKCS12");
    ks.load(new FileInputStream(keystoreLocation), keyPassphrase);

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

    char[] trustPassphrase = "rabbitstore".toCharArray();
    KeyStore tks = KeyStore.getInstance("JKS");
    tks.load(new FileInputStream(truststoreLocation), trustPassphrase);

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    tmf.init(tks);

    SSLContext c = SSLContext.getInstance("SSL");
    c.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    factory.setPort(5671);
    factory.useSslProtocol(c);

    Connection conn = factory.newConnection();
    Channel channel = conn.createChannel();

    GetResponse chResponse = channel.basicGet("WithClientCertQueue", true);
    if (chResponse != null) {
        byte[] body = chResponse.getBody();
        result = new String(body);
    }
    channel.close();
    conn.close();
    return result;
}

From source file:org.apache.bookkeeper.tls.TLSContextFactory.java

private KeyManagerFactory initKeyManagerFactory(String keyStoreType, String keyStoreLocation,
        String keyStorePasswordPath) throws SecurityException, KeyStoreException, NoSuchAlgorithmException,
        CertificateException, IOException, UnrecoverableKeyException, InvalidKeySpecException {
    KeyManagerFactory kmf = null;

    if (Strings.isNullOrEmpty(keyStoreLocation)) {
        LOG.error("Key store location cannot be empty when Mutual Authentication is enabled!");
        throw new SecurityException(
                "Key store location cannot be empty when Mutual Authentication is enabled!");
    }/*w  ww .j ava2s  .c  om*/

    String keyStorePassword = "";
    if (!Strings.isNullOrEmpty(keyStorePasswordPath)) {
        keyStorePassword = getPasswordFromFile(keyStorePasswordPath);
    }

    // Initialize key file
    KeyStore ks = loadKeyStore(keyStoreType, keyStoreLocation, keyStorePassword);
    kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(ks, keyStorePassword.trim().toCharArray());

    return kmf;
}

From source file:org.apache.camel.component.file.remote.FtpsEndpoint.java

/**
 * Create the FTPS client./*from   w  w  w . j a  v  a  2 s.  c o  m*/
 */
protected FTPClient createFtpClient() throws Exception {
    FTPSClient client = null;

    if (sslContextParameters != null) {
        SSLContext context = sslContextParameters.createSSLContext();

        client = new FTPSClient(getFtpsConfiguration().isImplicit(), context);

        // The FTPSClient tries to manage the following SSLSocket related configuration options
        // on its own based on internal configuration options.  FTPSClient does not lend itself
        // to subclassing for the purpose of overriding this behavior (private methods, fields, etc.).
        // As such, we create a socket (preconfigured by SSLContextParameters) from the context
        // we gave to FTPSClient and then setup FTPSClient to reuse the already configured configuration
        // from the socket for all future sockets it creates.  Not sexy and a little brittle, but it works.
        SSLSocket socket = (SSLSocket) context.getSocketFactory().createSocket();
        client.setEnabledCipherSuites(socket.getEnabledCipherSuites());
        client.setEnabledProtocols(socket.getEnabledProtocols());
        client.setNeedClientAuth(socket.getNeedClientAuth());
        client.setWantClientAuth(socket.getWantClientAuth());
        client.setEnabledSessionCreation(socket.getEnableSessionCreation());
    } else {
        client = new FTPSClient(getFtpsConfiguration().getSecurityProtocol(),
                getFtpsConfiguration().isImplicit());

        if (ftpClientKeyStoreParameters != null) {
            String type = (ftpClientKeyStoreParameters.containsKey("type"))
                    ? (String) ftpClientKeyStoreParameters.get("type")
                    : KeyStore.getDefaultType();
            String file = (String) ftpClientKeyStoreParameters.get("file");
            String password = (String) ftpClientKeyStoreParameters.get("password");
            String algorithm = (ftpClientKeyStoreParameters.containsKey("algorithm"))
                    ? (String) ftpClientKeyStoreParameters.get("algorithm")
                    : KeyManagerFactory.getDefaultAlgorithm();
            String keyPassword = (String) ftpClientKeyStoreParameters.get("keyPassword");

            KeyStore keyStore = KeyStore.getInstance(type);
            FileInputStream keyStoreFileInputStream = new FileInputStream(new File(file));
            try {
                keyStore.load(keyStoreFileInputStream, password.toCharArray());
            } finally {
                IOHelper.close(keyStoreFileInputStream, "keyStore", log);
            }

            KeyManagerFactory keyMgrFactory = KeyManagerFactory.getInstance(algorithm);
            keyMgrFactory.init(keyStore, keyPassword.toCharArray());
            client.setNeedClientAuth(true);
            client.setKeyManager(keyMgrFactory.getKeyManagers()[0]);
        }

        if (ftpClientTrustStoreParameters != null) {
            String type = (ftpClientTrustStoreParameters.containsKey("type"))
                    ? (String) ftpClientTrustStoreParameters.get("type")
                    : KeyStore.getDefaultType();
            String file = (String) ftpClientTrustStoreParameters.get("file");
            String password = (String) ftpClientTrustStoreParameters.get("password");
            String algorithm = (ftpClientTrustStoreParameters.containsKey("algorithm"))
                    ? (String) ftpClientTrustStoreParameters.get("algorithm")
                    : TrustManagerFactory.getDefaultAlgorithm();

            KeyStore trustStore = KeyStore.getInstance(type);
            FileInputStream trustStoreFileInputStream = new FileInputStream(new File(file));
            try {
                trustStore.load(trustStoreFileInputStream, password.toCharArray());
            } finally {
                IOHelper.close(trustStoreFileInputStream, "trustStore", log);
            }

            TrustManagerFactory trustMgrFactory = TrustManagerFactory.getInstance(algorithm);
            trustMgrFactory.init(trustStore);

            client.setTrustManager(trustMgrFactory.getTrustManagers()[0]);
        }
    }

    return client;
}

From source file:com.openmeap.util.SSLUtils.java

public static KeyManager[] getDefaultKeyManagers(KeyStore keyStore, String password)
        throws NoSuchAlgorithmException, UnrecoverableKeyException, KeyStoreException {

    // now we have to initialize the KeyManagers too
    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, password.toCharArray());
    return keyManagerFactory.getKeyManagers();
}

From source file:com.predic8.membrane.core.transport.ssl.SSLContext.java

public SSLContext(SSLParser sslParser, ResolverMap resourceResolver, String baseLocation) {
    this.sslParser = sslParser;
    try {//from w  ww  .  j  a  va 2 s .c om
        String algorihm = KeyManagerFactory.getDefaultAlgorithm();
        if (sslParser.getAlgorithm() != null)
            algorihm = sslParser.getAlgorithm();

        KeyManagerFactory kmf = null;
        String keyStoreType = "JKS";
        if (sslParser.getKeyStore() != null) {
            if (sslParser.getKeyStore().getKeyAlias() != null)
                throw new InvalidParameterException("keyAlias is not yet supported.");
            char[] keyPass = "changeit".toCharArray();
            if (sslParser.getKeyStore().getKeyPassword() != null)
                keyPass = sslParser.getKeyStore().getKeyPassword().toCharArray();

            if (sslParser.getKeyStore().getType() != null)
                keyStoreType = sslParser.getKeyStore().getType();
            KeyStore ks = openKeyStore(sslParser.getKeyStore(), "JKS", keyPass, resourceResolver, baseLocation);
            kmf = KeyManagerFactory.getInstance(algorihm);
            kmf.init(ks, keyPass);

            Enumeration<String> aliases = ks.aliases();
            while (aliases.hasMoreElements()) {
                String alias = aliases.nextElement();
                if (ks.isKeyEntry(alias)) {
                    // first key is used by the KeyManagerFactory
                    Certificate c = ks.getCertificate(alias);
                    if (c instanceof X509Certificate) {
                        X509Certificate x = (X509Certificate) c;

                        dnsNames = new ArrayList<String>();

                        Collection<List<?>> subjectAlternativeNames = x.getSubjectAlternativeNames();
                        if (subjectAlternativeNames != null)
                            for (List<?> l : subjectAlternativeNames) {
                                if (l.get(0) instanceof Integer && ((Integer) l.get(0) == 2))
                                    dnsNames.add(l.get(1).toString());
                            }
                    }
                    break;
                }
            }

        }
        TrustManagerFactory tmf = null;
        if (sslParser.getTrustStore() != null) {
            String trustAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
            if (sslParser.getTrustStore().getAlgorithm() != null)
                trustAlgorithm = sslParser.getTrustStore().getAlgorithm();
            KeyStore ks = openKeyStore(sslParser.getTrustStore(), keyStoreType, null, resourceResolver,
                    baseLocation);
            tmf = TrustManagerFactory.getInstance(trustAlgorithm);
            tmf.init(ks);
        }

        TrustManager[] tms = tmf != null ? tmf.getTrustManagers()
                : null /* trust anyone: new TrustManager[] { new NullTrustManager() } */;
        if (sslParser.isIgnoreTimestampCheckFailure())
            tms = new TrustManager[] { new TrustManagerWrapper(tms, true) };

        if (sslParser.getProtocol() != null)
            sslc = javax.net.ssl.SSLContext.getInstance(sslParser.getProtocol());
        else
            sslc = javax.net.ssl.SSLContext.getInstance("TLS");

        sslc.init(kmf != null ? kmf.getKeyManagers() : null, tms, null);

        if (sslParser.getCiphers() != null) {
            ciphers = sslParser.getCiphers().split(",");
            Set<String> supportedCiphers = Sets.newHashSet(sslc.getSocketFactory().getSupportedCipherSuites());
            for (String cipher : ciphers) {
                if (!supportedCiphers.contains(cipher))
                    throw new InvalidParameterException("Unknown cipher " + cipher);
                if (cipher.contains("_RC4_"))
                    log.warn("Cipher " + cipher + " uses RC4, which is deprecated.");
            }
        } else {
            // use all default ciphers except those using RC4
            String supportedCiphers[] = sslc.getSocketFactory().getDefaultCipherSuites();
            ArrayList<String> ciphers = new ArrayList<String>(supportedCiphers.length);
            for (String cipher : supportedCiphers)
                if (!cipher.contains("_RC4_"))
                    ciphers.add(cipher);
            sortCiphers(ciphers);
            this.ciphers = ciphers.toArray(new String[ciphers.size()]);
        }
        if (setUseCipherSuitesOrderMethod == null)
            log.warn(
                    "Cannot set the cipher suite order before Java 8. This prevents Forward Secrecy with some SSL clients.");

        if (sslParser.getProtocols() != null) {
            protocols = sslParser.getProtocols().split(",");
        } else {
            protocols = null;
        }

        if (sslParser.getClientAuth() == null) {
            needClientAuth = false;
            wantClientAuth = false;
        } else if (sslParser.getClientAuth().equals("need")) {
            needClientAuth = true;
            wantClientAuth = true;
        } else if (sslParser.getClientAuth().equals("want")) {
            needClientAuth = false;
            wantClientAuth = true;
        } else {
            throw new RuntimeException("Invalid value '" + sslParser.getClientAuth()
                    + "' in clientAuth: expected 'want', 'need' or not set.");
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:davmail.http.DavGatewaySSLProtocolSocketFactory.java

private SSLContext createSSLContext() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException,
        KeyManagementException, KeyStoreException {
    // PKCS11 client certificate settings
    String pkcs11Library = Settings.getProperty("davmail.ssl.pkcs11Library");

    String clientKeystoreType = Settings.getProperty("davmail.ssl.clientKeystoreType");
    // set default keystore type
    if (clientKeystoreType == null || clientKeystoreType.length() == 0) {
        clientKeystoreType = "PKCS11";
    }/*from w  w w. j  ava 2  s .  c o m*/

    if (pkcs11Library != null && pkcs11Library.length() > 0 && "PKCS11".equals(clientKeystoreType)) {
        StringBuilder pkcs11Buffer = new StringBuilder();
        pkcs11Buffer.append("name=DavMail\n");
        pkcs11Buffer.append("library=").append(pkcs11Library).append('\n');
        String pkcs11Config = Settings.getProperty("davmail.ssl.pkcs11Config");
        if (pkcs11Config != null && pkcs11Config.length() > 0) {
            pkcs11Buffer.append(pkcs11Config).append('\n');
        }
        SunPKCS11ProviderHandler.registerProvider(pkcs11Buffer.toString());
    }

    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(/*KeyManagerFactory.getDefaultAlgorithm()*/"NewSunX509");

    ArrayList<KeyStore.Builder> keyStoreBuilders = new ArrayList<KeyStore.Builder>();
    // PKCS11 (smartcard) keystore with password callback
    KeyStore.Builder scBuilder = KeyStore.Builder.newInstance("PKCS11", null, getProtectionParameter(null));
    keyStoreBuilders.add(scBuilder);

    String clientKeystoreFile = Settings.getProperty("davmail.ssl.clientKeystoreFile");
    String clientKeystorePass = Settings.getProperty("davmail.ssl.clientKeystorePass");
    if (clientKeystoreFile != null && clientKeystoreFile.length() > 0
            && ("PKCS12".equals(clientKeystoreType) || "JKS".equals(clientKeystoreType))) {
        // PKCS12 file based keystore
        KeyStore.Builder fsBuilder = KeyStore.Builder.newInstance(clientKeystoreType, null,
                new File(clientKeystoreFile), getProtectionParameter(clientKeystorePass));
        keyStoreBuilders.add(fsBuilder);
    }

    ManagerFactoryParameters keyStoreBuilderParameters = new KeyStoreBuilderParameters(keyStoreBuilders);
    keyManagerFactory.init(keyStoreBuilderParameters);

    // Get a list of key managers
    KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();

    // Walk through the key managers and replace all X509 Key Managers with
    // a specialized wrapped DavMail X509 Key Manager
    for (int i = 0; i < keyManagers.length; i++) {
        KeyManager keyManager = keyManagers[i];
        if (keyManager instanceof X509KeyManager) {
            keyManagers[i] = new DavMailX509KeyManager((X509KeyManager) keyManager);
        }
    }

    SSLContext context = SSLContext.getInstance("SSL");
    context.init(keyManagers, new TrustManager[] { new DavGatewayX509TrustManager() }, null);
    return context;
}

From source file:org.apache.ranger.services.nifi.client.NiFiConnectionMgr.java

private static SSLContext createSslContext(final String keystore, final char[] keystorePasswd,
        final String keystoreType, final String truststore, final char[] truststorePasswd,
        final String truststoreType, final String protocol) throws KeyStoreException, IOException,
        NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException, KeyManagementException {

    // prepare the keystore
    final KeyStore keyStore = KeyStore.getInstance(keystoreType);
    try (final InputStream keyStoreStream = new FileInputStream(keystore)) {
        keyStore.load(keyStoreStream, keystorePasswd);
    }/*  w  ww .  j  av  a 2  s .  co m*/
    final KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, keystorePasswd);

    // prepare the truststore
    final KeyStore trustStore = KeyStore.getInstance(truststoreType);
    try (final InputStream trustStoreStream = new FileInputStream(truststore)) {
        trustStore.load(trustStoreStream, truststorePasswd);
    }
    final TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(trustStore);

    // initialize the ssl context
    final SSLContext sslContext = SSLContext.getInstance(protocol);
    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
            new SecureRandom());
    return sslContext;
}

From source file:talkeeg.httpserver.HttpServer.java

private NHttpConnectionFactory<DefaultNHttpServerConnection> createConnectionFactory() {
    NHttpConnectionFactory<DefaultNHttpServerConnection> connFactory;
    if (config.isUseTLS()) {
        try {// w  w  w. j  av  a  2 s  . c  o m
            KeyStore keystore = KeyStore.getInstance("jks");
            char[] password = new char[0];
            keystore.load(null, password);
            final X509Certificate certificate = certManager.getCertificate(OwnedKeyType.USER);
            KeyStore.PrivateKeyEntry entry = new KeyStore.PrivateKeyEntry(
                    ownedKeysManager.getPrivateKey(OwnedKeyType.USER), new Certificate[] { certificate });

            keystore.setEntry("", entry, new KeyStore.PasswordProtection(password));
            KeyManagerFactory kmfactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmfactory.init(keystore, password);
            final KeyManager[] keymanagers = kmfactory.getKeyManagers();
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(keymanagers, null, null);
            connFactory = new SSLNHttpServerConnectionFactory(sslcontext, null, ConnectionConfig.DEFAULT);
        } catch (Exception e) {
            throw new RuntimeException("Can not initialise SSL.", e);
        }
    } else {
        connFactory = new DefaultNHttpServerConnectionFactory(ConnectionConfig.DEFAULT);
    }
    return connFactory;
}

From source file:org.kuali.mobility.push.dao.PushDaoImpl.java

private SSLSocket openConnectionToAPNS(String host, int port, String key, String passphrase) {
    SSLSocket socket;// w  w  w . ja  va  2 s.  co  m
    try {
        KeyStore keyStore = KeyStore.getInstance("PKCS12");

        //          keyStore.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("newcert.p12"), "strange word to use".toCharArray());
        //          keyStore.load(getClass().getResourceAsStream("/newcert.p12"), "strange word to use".toCharArray());
        //          keyStore.load(this.getClass().getClassLoader().getResourceAsStream("newcert.p12"), "strange word to use".toCharArray());

        // This works when built with Eclipse, but not when built from command line. 
        // Has to do with where the build system puts /resources/*.p12 file
        //          keyStore.load(this.getClass().getClassLoader().getResourceAsStream(key), "strange word to use".toCharArray());

        // Currently only works when read from the server's FS. Won't currently read from within eclipse project. 
        // Putting it in /opt/kme/push prevents naming conflicts. 
        keyStore.load(new FileInputStream("/opt/kme/push/newcert.p12"), "strange word to use".toCharArray());

        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("sunx509");
        keyManagerFactory.init(keyStore, "strange word to use".toCharArray());
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("sunx509");
        trustManagerFactory.init(keyStore);
        SSLContext sslCtx = SSLContext.getInstance("TLS");
        sslCtx.init(keyManagerFactory.getKeyManagers(), null, null);
        SSLSocketFactory sslSocketFactory = sslCtx.getSocketFactory();
        socket = (SSLSocket) sslSocketFactory.createSocket(host, port);
        socket.startHandshake();

        //Diagnostic output
        Enumeration e = keyStore.aliases();
        LOG.info(e.toString());
        while (e.hasMoreElements()) {
            LOG.info("Alias: " + e.nextElement().toString());
        }

        String not = (socket.isConnected()) ? "" : "NOT ";
        LOG.info("SSLSocket is " + not + "Connected");

        LOG.info("Connected to: " + socket.getInetAddress().getCanonicalHostName());
        LOG.info("Connected to: " + socket.getInetAddress().getHostAddress());

        String cs[] = socket.getEnabledCipherSuites();
        LOG.info("CipherSuites: " + Arrays.toString(cs));

        String ep[] = socket.getEnabledProtocols();
        LOG.info("Enabled Protocols: " + Arrays.toString(ep));

        LOG.info("Timeout: " + socket.getSoTimeout());
        LOG.info("Send Buffer Size: " + socket.getSendBufferSize());

        return socket;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.eclipse.emf.emfstore.server.connection.ServerKeyStoreManager.java

/**
 * Creates a {@link KeyManagerFactory} for the rmi encryption (
 * {@link org.eclipse.emf.emfstore.server.connection.rmi.RMISSLServerSocketFactory} ).
 * /*w ww .  ja v  a2s.  c om*/
 * @return KeyManagerFactory
 * @throws ServerKeyStoreException in case of failure
 */
public KeyManagerFactory getKeyManagerFactory() throws ServerKeyStoreException {
    try {
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(
                ServerConfiguration.getProperties().getProperty(ServerConfiguration.KEYSTORE_CERTIFICATE_TYPE,
                        ServerConfiguration.KEYSTORE_CERTIFICATE_TYPE_DEFAULT));
        keyManagerFactory.init(getKeyStore(), getKeyStorePassword());
        return keyManagerFactory;
    } catch (NoSuchAlgorithmException e) {
        throw new ServerKeyStoreException(e);
    } catch (KeyStoreException e) {
        throw new ServerKeyStoreException(e);
    } catch (UnrecoverableKeyException e) {
        throw new ServerKeyStoreException(e);
    }
}