Example usage for javax.net.ssl KeyManagerFactory getKeyManagers

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

Introduction

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

Prototype

public final KeyManager[] getKeyManagers() 

Source Link

Document

Returns one key manager for each type of key material.

Usage

From source file:org.xdi.net.SslDefaultHttpClient.java

private KeyManager[] getKeyManagers() throws Exception {
    KeyStore keyStore = getKeyStore(this.keyStoreType, this.keyStorePath, this.keyStorePassword);

    KeyManagerFactory kmFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmFactory.init(keyStore, this.keyStorePassword.toCharArray());

    return kmFactory.getKeyManagers();
}

From source file:com.ibm.iotf.client.AbstractClient.java

static SSLSocketFactory getSocketFactory(final String caCrtFile, final String crtFile, final String keyFile,
        final String password) throws IOException, KeyStoreException, NoSuchAlgorithmException,
        CertificateException, UnrecoverableKeyException, KeyManagementException {
    Security.addProvider(new BouncyCastleProvider());
    X509Certificate caCert = null;

    if (caCrtFile != null) {
        // load CA certificate
        PEMReader reader = new PEMReader(
                new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(caCrtFile)))));
        caCert = (X509Certificate) reader.readObject();
        reader.close();/*from ww  w .jav a2 s .  c  om*/
    } else {
        ClassLoader classLoader = AbstractClient.class.getClassLoader();
        PEMReader reader = new PEMReader(
                new InputStreamReader(classLoader.getResource(SERVER_MESSAGING_PEM).openStream()));
        caCert = (X509Certificate) reader.readObject();
        reader.close();
    }

    PEMReader reader = new PEMReader(
            new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(crtFile)))));
    X509Certificate cert = (X509Certificate) reader.readObject();
    reader.close();

    // load client private key
    reader = new PEMReader(
            new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(keyFile)))));
    KeyPair key = (KeyPair) reader.readObject();
    reader.close();

    TrustManagerFactory tmf = null;
    if (caCert != null) {
        // CA certificate is used to authenticate server
        KeyStore caKs = KeyStore.getInstance("JKS");
        //caKs.load(null, null);
        caKs.load(null, null);
        caKs.setCertificateEntry("ca-certificate", caCert);
        tmf = TrustManagerFactory.getInstance("PKIX");
        tmf.init(caKs);
    }
    // client key and certificates are sent to server so it can authenticate us
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);
    ks.setCertificateEntry("certificate", cert);
    ks.setKeyEntry("private-key", key.getPrivate(), password.toCharArray(),
            new java.security.cert.Certificate[] { cert });
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("PKIX");
    kmf.init(ks, password.toCharArray());

    // finally, create SSL socket factory
    SSLContext context = SSLContext.getInstance("TLSv1.2");
    if (tmf != null) {
        context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    } else {
        context.init(kmf.getKeyManagers(), null, null);
    }

    return context.getSocketFactory();
}

From source file:com.terradue.warhol.auth.ssl.SslAuthenticationConfiguration.java

private KeyManager[] fromSslKeyAndCertificate(String publicCertificateLocation, String provateKeyLocation,
        String sslPassword) {//from  ww  w.java  2 s .  com
    File publicCertificate = checkFile(publicCertificateLocation);
    File privateKey = checkFile(provateKeyLocation);

    char[] password;
    if (sslPassword != null) {
        password = sslPassword.toCharArray();
    } else {
        password = new char[] {};
    }

    try {
        final KeyStore store = new KeyMaterial(publicCertificate, privateKey, 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 IllegalStateException("Impossible to initialize SSL certificate/key", e);
    }
}

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   w  w  w.j av  a  2s . 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:org.eclipse.mylyn.internal.commons.http.PollingSslProtocolSocketFactory.java

public PollingSslProtocolSocketFactory() {
    KeyManager[] keymanagers = null;
    if (System.getProperty(KEY_STORE) != null && System.getProperty(KEY_STORE_PASSWORD) != null) {
        try {/*from w  ww .  j  ava  2 s  . c  om*/
            String type = System.getProperty(KEY_STORE_TYPE, KeyStore.getDefaultType());
            KeyStore keyStore = KeyStore.getInstance(type);
            char[] password = System.getProperty(KEY_STORE_PASSWORD).toCharArray();
            keyStore.load(new FileInputStream(System.getProperty(KEY_STORE)), password);
            KeyManagerFactory keyManagerFactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(keyStore, password);
            keymanagers = keyManagerFactory.getKeyManagers();
        } catch (Exception e) {
            CommonsHttpPlugin.log(IStatus.ERROR, "Could not initialize keystore", e); //$NON-NLS-1$
        }
    }

    hasKeyManager = keymanagers != null;

    try {
        SSLContext sslContext = SSLContext.getInstance("SSL"); //$NON-NLS-1$
        sslContext.init(keymanagers, new TrustManager[] { new TrustAllTrustManager() }, null);
        this.socketFactory = sslContext.getSocketFactory();
    } catch (Exception e) {
        CommonsHttpPlugin.log(IStatus.ERROR, "Could not initialize SSL context", e); //$NON-NLS-1$
    }
}

From source file:talkeeg.httpserver.HttpServer.java

private NHttpConnectionFactory<DefaultNHttpServerConnection> createConnectionFactory() {
    NHttpConnectionFactory<DefaultNHttpServerConnection> connFactory;
    if (config.isUseTLS()) {
        try {/*from  w w  w. ja  va2 s . co 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:ddf.security.settings.impl.SecuritySettingsServiceImpl.java

@Override
public TLSClientParameters getTLSParameters() {
    TLSClientParameters tlsParams = new TLSClientParameters();
    try {//from   w  ww  .  ja  v a2 s  .c  o  m
        TrustManagerFactory trustFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustFactory.init(trustStore);
        TrustManager[] tm = trustFactory.getTrustManagers();
        tlsParams.setTrustManagers(tm);

        KeyManagerFactory keyFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyFactory.init(keyStore, keystorePassword.toCharArray());
        KeyManager[] km = keyFactory.getKeyManagers();
        tlsParams.setKeyManagers(km);
    } catch (NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException e) {
        LOGGER.warn(
                "Could not fully load keystore/truststore into TLSParameters. Parameters may not be fully functional.",
                e);
    }

    FiltersType filter = new FiltersType();
    filter.getInclude().addAll(SSL_ALLOWED_ALGORITHMS);
    filter.getExclude().addAll(SSL_DISALLOWED_ALGORITHMS);
    tlsParams.setCipherSuitesFilter(filter);

    return tlsParams;
}

From source file:com.linkedin.pinot.common.utils.ClientSSLContextGenerator.java

private KeyManager[] setupKeyManagers() {
    if (_keyStoreFile == null) {
        return null;
    }//from w  ww .  j a  va2s.  c o  m
    try {
        KeyStore keyStore = KeyStore.getInstance(KEYSTORE_TYPE);
        LOGGER.info("Setting up keystore with file {}", _keyStoreFile);
        keyStore.load(new FileInputStream(new File(_keyStoreFile)), _keyStorePassword.toCharArray());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KEYMANAGER_FACTORY_ALGORITHM);
        kmf.init(keyStore, _keyStorePassword.toCharArray());
        LOGGER.info("Successfully initialized keystore");
        return kmf.getKeyManagers();
    } catch (Exception e) {
        Utils.rethrowException(e);
    }
    return null;
}

From source file:test.integ.be.fedict.trust.SSLTrustValidatorTest.java

@Test
public void testTestEIDBelgiumBe() throws Exception {
    Security.addProvider(new BeIDProvider());

    SSLContext sslContext = SSLContext.getInstance("TLS");
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("BeID");

    keyManagerFactory.init(null);/*from  ww  w. j  a  va2  s.c o m*/
    SecureRandom secureRandom = new SecureRandom();
    sslContext.init(keyManagerFactory.getKeyManagers(), new TrustManager[] { new ClientTestX509TrustManager() },
            secureRandom);
    SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
    SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket("test.eid.belgium.be", 443);
    LOG.debug("socket created");
    SSLSession sslSession = sslSocket.getSession();
    Certificate[] peerCertificates = sslSession.getPeerCertificates();
    for (Certificate peerCertificate : peerCertificates) {
        LOG.debug("peer certificate: " + ((X509Certificate) peerCertificate).getSubjectX500Principal());
    }

    MemoryCertificateRepository repository = new MemoryCertificateRepository();
    repository.addTrustPoint((X509Certificate) peerCertificates[peerCertificates.length - 1]);

    TrustValidator trustValidator = new TrustValidator(repository);
    TrustValidatorDecorator trustValidatorDecorator = new TrustValidatorDecorator();
    trustValidatorDecorator.addDefaultTrustLinkerConfig(trustValidator);
    trustValidator.isTrusted(peerCertificates);
}

From source file:org.elasticsearch.hadoop.rest.commonshttp.SSLSocketFactory.java

private KeyManager[] loadKeyManagers() throws GeneralSecurityException, IOException {
    if (!StringUtils.hasText(keyStoreLocation)) {
        return null;
    }/*w w  w .  ja  v a  2  s  .c om*/

    char[] pass = (StringUtils.hasText(keyStorePass) ? keyStorePass.trim().toCharArray() : null);
    KeyStore keyStore = loadKeyStore(keyStoreLocation, pass);
    KeyManagerFactory kmFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmFactory.init(keyStore, pass);
    return kmFactory.getKeyManagers();
}