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.wildfly.elytron.web.undertow.server.ClientCertAuthenticationTest.java

/**
 * Get the key manager backed by the specified key store.
 *
 * @param keystoreName the name of the key store to load.
 * @return the initialised key manager./*  ww w .  j  a v a  2s  . c o m*/
 */
private X509ExtendedKeyManager getKeyManager(final String keystorePath) throws Exception {
    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(loadKeyStore(keystorePath), "Elytron".toCharArray());

    for (KeyManager current : keyManagerFactory.getKeyManagers()) {
        if (current instanceof X509ExtendedKeyManager) {
            return (X509ExtendedKeyManager) current;
        }
    }

    throw new IllegalStateException("Unable to obtain X509ExtendedKeyManager.");
}

From source file:com.gargoylesoftware.htmlunit.httpclient.HtmlUnitSSLConnectionSocketFactory.java

private static KeyManager[] getKeyManagers(final WebClientOptions options) {
    if (options.getSSLClientCertificateStore() == null) {
        return null;
    }//from w  ww.  j av a2 s .c om
    try {
        final KeyStore keyStore = options.getSSLClientCertificateStore();
        final KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, options.getSSLClientCertificatePassword());
        return keyManagerFactory.getKeyManagers();
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.opcfoundation.ua.transport.https.HttpsSettings.java

/**
 * Set keystore as the key manager for a https application.   
 *  /*from w w  w  .j av  a2s .com*/
 * @param keystore
 * @param password
 * @throws NoSuchAlgorithmException
 * @throws UnrecoverableKeyException
 * @throws KeyStoreException
 */
public void setKeyStore(KeyStore keystore, String password) throws ServiceResultException {
    try {
        KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmfactory.init(keystore, password.toCharArray());
        KeyManager kms[] = kmfactory.getKeyManagers();
        keyManager = kms.length == 0 ? null : (X509KeyManager) kms[0];
    } catch (NoSuchAlgorithmException e) {
        throw new ServiceResultException(e);
    } catch (UnrecoverableKeyException e) {
        throw new ServiceResultException(e);
    } catch (KeyStoreException e) {
        throw new ServiceResultException(e);
    }
}

From source file:se.vgregion.delegation.server.Server.java

/**
 * This method sets up the security./*from   ww  w.  ja  v  a  2s  . c o m*/
 * 
 * @param port
 * @throws IOException
 * @throws GeneralSecurityException
 */
private void setupServerEngineFactory(int port) throws IOException, GeneralSecurityException {

    TLSServerParameters tlsParams = new TLSServerParameters();

    String userhome = System.getProperty("user.home");
    String certFilePath = userhome + "/.delegation-service/" + propertiesBean.getCertFileName();

    // String trustStoreFilePath = userhome + "/.delegation-service/prod-truststore.jks";
    String trustStoreFilePath = userhome + "/.delegation-service/" + propertiesBean.getClientAuthCertFilename();

    InputStream resourceAsStream = new FileInputStream(certFilePath);

    KeyStore keyStore = KeyStore.getInstance("PKCS12");

    try {
        keyStore.load(resourceAsStream, propertiesBean.getCertPass().toCharArray());
    } finally {
        resourceAsStream.close();
    }

    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
    keyManagerFactory.init(keyStore, propertiesBean.getCertPass().toCharArray());
    tlsParams.setKeyManagers(keyManagerFactory.getKeyManagers());

    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
    // trustManagerFactory.init(keyStore);

    InputStream is = new FileInputStream(trustStoreFilePath);
    KeyStore trustStore = KeyStore.getInstance("JKS");
    // trustStore.load(is, "password".toCharArray());
    trustStore.load(is, propertiesBean.getClientAuthCertPass().toCharArray());
    trustManagerFactory.init(trustStore);
    TrustManager[] trustMgrs = trustManagerFactory.getTrustManagers();

    tlsParams.setTrustManagers(trustMgrs);

    // FiltersType filter = new FiltersType();
    // filter.getInclude().add(".*");
    // tlsParams.setCipherSuitesFilter(filter);

    ClientAuthentication clientAuth = new ClientAuthentication();
    // clientAuth.setRequired(true);
    // clientAuth.setWant(true);
    clientAuth.setRequired(true);
    clientAuth.setWant(false);
    tlsParams.setClientAuthentication(clientAuth);

    // if (propertiesBean.isClientCertSecurityActive()) {
    // CertificateConstraintsType constraints = new CertificateConstraintsType();
    // DNConstraintsType constraintsType = new DNConstraintsType();
    // // constraintsType.setCombinator(CombinatorType.ANY);
    // System.out.println("propertiesBean.getRegularExpressionClientCert() "
    // + propertiesBean.getRegularExpressionClientCert());
    // String regularExpression = propertiesBean.getRegularExpressionClientCert();
    // // constraintsType.getRegularExpression().add(regularExpression);
    // constraints.setSubjectDNConstraints(constraintsType);
    // tlsParams.setCertConstraints(constraints);
    // }

    engineFactory = new JettyHTTPServerEngineFactory();
    engineFactory.setTLSServerParametersForPort(port, tlsParams);

}

From source file:org.eclipse.mylyn.internal.commons.net.PollingSslProtocolSocketFactory.java

private KeyManager[] openKeyStore(String type) throws KeyStoreException, IOException, NoSuchAlgorithmException,
        CertificateException, FileNotFoundException, UnrecoverableKeyException {
    KeyStore keyStore = KeyStore.getInstance(type);
    char[] password = keyStorePassword.toCharArray();
    keyStore.load(new FileInputStream(keyStoreFileName), password);
    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, password);
    return keyManagerFactory.getKeyManagers();
}

From source file:org.jenkinsci.remoting.engine.HandlerLoopbackLoadStress.java

public HandlerLoopbackLoadStress(Config config)
        throws IOException, NoSuchAlgorithmException, CertificateException, KeyStoreException,
        UnrecoverableKeyException, KeyManagementException, OperatorCreationException {
    this.config = config;
    KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
    gen.initialize(2048); // maximum supported by JVM with export restrictions
    keyPair = gen.generateKeyPair();//from  w w w  . ja  va  2s.c o  m

    Date now = new Date();
    Date firstDate = new Date(now.getTime() + TimeUnit.DAYS.toMillis(10));
    Date lastDate = new Date(now.getTime() + TimeUnit.DAYS.toMillis(-10));

    SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo
            .getInstance(keyPair.getPublic().getEncoded());

    X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
    X500Name subject = nameBuilder.addRDN(BCStyle.CN, getClass().getSimpleName()).addRDN(BCStyle.C, "US")
            .build();

    X509v3CertificateBuilder certGen = new X509v3CertificateBuilder(subject, BigInteger.ONE, firstDate,
            lastDate, subject, subjectPublicKeyInfo);

    JcaX509ExtensionUtils instance = new JcaX509ExtensionUtils();

    certGen.addExtension(X509Extension.subjectKeyIdentifier, false,
            instance.createSubjectKeyIdentifier(subjectPublicKeyInfo));

    ContentSigner signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(BOUNCY_CASTLE_PROVIDER)
            .build(keyPair.getPrivate());

    certificate = new JcaX509CertificateConverter().setProvider(BOUNCY_CASTLE_PROVIDER)
            .getCertificate(certGen.build(signer));

    char[] password = "password".toCharArray();

    KeyStore store = KeyStore.getInstance("jks");
    store.load(null, password);
    store.setKeyEntry("alias", keyPair.getPrivate(), password, new Certificate[] { certificate });

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(store, password);

    context = SSLContext.getInstance("TLS");
    context.init(kmf.getKeyManagers(), new TrustManager[] { new BlindTrustX509ExtendedTrustManager() }, null);

    mainHub = IOHub.create(executorService);
    // on windows there is a bug whereby you cannot mix ServerSockets and Sockets on the same selector
    acceptorHub = File.pathSeparatorChar == 59 ? IOHub.create(executorService) : mainHub;
    legacyHub = new NioChannelHub(executorService);
    executorService.submit(legacyHub);
    serverSocketChannel = ServerSocketChannel.open();

    JnlpProtocolHandler handler = null;
    for (JnlpProtocolHandler h : new JnlpProtocolHandlerFactory(executorService).withNioChannelHub(legacyHub)
            .withIOHub(mainHub).withSSLContext(context).withPreferNonBlockingIO(!config.bio)
            .withClientDatabase(new JnlpClientDatabase() {
                @Override
                public boolean exists(String clientName) {
                    return true;
                }

                @Override
                public String getSecretOf(@Nonnull String clientName) {
                    return secretFor(clientName);
                }
            }).withSSLClientAuthRequired(false).handlers()) {
        if (config.name.equals(h.getName())) {
            handler = h;
            break;
        }
    }
    if (handler == null) {
        throw new RuntimeException("Unknown handler: " + config.name);
    }
    this.handler = handler;

    acceptor = new Acceptor(serverSocketChannel);
    runtimeMXBean = ManagementFactory.getRuntimeMXBean();
    operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
    _getProcessCpuTime = _getProcessCpuTime(operatingSystemMXBean);
    garbageCollectorMXBeans = new ArrayList<GarbageCollectorMXBean>(
            ManagementFactory.getGarbageCollectorMXBeans());
    Collections.sort(garbageCollectorMXBeans, new Comparator<GarbageCollectorMXBean>() {
        @Override
        public int compare(GarbageCollectorMXBean o1, GarbageCollectorMXBean o2) {
            return o1.getName().compareTo(o2.getName());
        }
    });
    stats = new Stats();
}

From source file:com.android.beyondemail.SSLSocketFactory.java

private static KeyManager[] createKeyManagers(final KeyStore keystore, final String password)
        throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
    if (keystore == null) {
        throw new IllegalArgumentException("Keystore may not be null");
    }//ww w .ja  va2 s  . c  o  m
    KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmfactory.init(keystore, password != null ? password.toCharArray() : null);
    return kmfactory.getKeyManagers();
}

From source file:org.apache.jmeter.util.JsseSSLManager.java

private SSLContext createContext() throws GeneralSecurityException {
    SSLContext context;/*from   w  ww .j a  v a2  s . co m*/
    if (pro != null) {
        context = SSLContext.getInstance(DEFAULT_SSL_PROTOCOL, pro); // $NON-NLS-1$
    } else {
        context = SSLContext.getInstance(DEFAULT_SSL_PROTOCOL); // $NON-NLS-1$
    }
    KeyManagerFactory managerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    JmeterKeyStore keys = this.getKeyStore();
    managerFactory.init(null, defaultpw == null ? new char[] {} : defaultpw.toCharArray());
    KeyManager[] managers = managerFactory.getKeyManagers();
    KeyManager[] newManagers = new KeyManager[managers.length];

    log.debug(keys.getClass().toString());

    // Now wrap the default managers with our key manager
    for (int i = 0; i < managers.length; i++) {
        if (managers[i] instanceof X509KeyManager) {
            X509KeyManager manager = (X509KeyManager) managers[i];
            newManagers[i] = new WrappedX509KeyManager(manager, keys);
        } else {
            newManagers[i] = managers[i];
        }
    }

    // Get the default trust managers
    TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmfactory.init(this.getTrustStore());

    // Wrap the defaults in our custom trust manager
    TrustManager[] trustmanagers = tmfactory.getTrustManagers();
    for (int i = 0; i < trustmanagers.length; i++) {
        if (trustmanagers[i] instanceof X509TrustManager) {
            trustmanagers[i] = new CustomX509TrustManager((X509TrustManager) trustmanagers[i]);
        }
    }
    context.init(newManagers, trustmanagers, this.rand);
    if (log.isDebugEnabled()) {
        String[] dCiphers = context.getSocketFactory().getDefaultCipherSuites();
        String[] sCiphers = context.getSocketFactory().getSupportedCipherSuites();
        int len = (dCiphers.length > sCiphers.length) ? dCiphers.length : sCiphers.length;
        for (int i = 0; i < len; i++) {
            if (i < dCiphers.length) {
                log.debug("Default Cipher: " + dCiphers[i]);
            }
            if (i < sCiphers.length) {
                log.debug("Supported Cipher: " + sCiphers[i]);
            }
        }
    }
    return context;
}

From source file:org.codice.ddf.spatial.ogc.catalog.common.TestTrustedRemoteSource.java

private TLSClientParameters getTLSParameters(KeyStore keyStore, String keystorePassword, KeyStore trustStore) {
    TLSClientParameters tlsParams = new TLSClientParameters();
    try {//from w  ww  . j a  v a  2  s .co 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 (Exception e) {
        LOGGER.warn("Could not load keystores, may be an error with the filesystem", e);
    }

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

    return tlsParams;
}

From source file:org.apache.hadoop.security.ssl.FileBasedKeyStoresFactory.java

private void createKeyManagers(SSLFactory.Mode mode) throws IOException, GeneralSecurityException {
    boolean requireClientCert = conf.getBoolean(SSLFactory.SSL_REQUIRE_CLIENT_CERT_KEY,
            SSLFactory.DEFAULT_SSL_REQUIRE_CLIENT_CERT);

    String keystoreType = conf.get(resolvePropertyName(mode, SSL_KEYSTORE_TYPE_TPL_KEY), DEFAULT_KEYSTORE_TYPE);

    if (requireClientCert || mode == SSLFactory.Mode.SERVER) {
        String locationProperty = resolvePropertyName(mode, SSL_KEYSTORE_LOCATION_TPL_KEY);
        String keystoreLocation = conf.get(locationProperty, "");
        if (keystoreLocation.isEmpty()) {
            throw new GeneralSecurityException(
                    "The property '" + locationProperty + "' has not been set in the ssl configuration file.");
        }//from  w  w  w . j a v a 2s  .  c  o  m
        String passwordProperty = resolvePropertyName(mode, SSL_KEYSTORE_PASSWORD_TPL_KEY);
        String keystorePassword = getPassword(conf, passwordProperty, "");
        if (keystorePassword.isEmpty()) {
            throw new GeneralSecurityException(
                    "The property '" + passwordProperty + "' has not been set in the ssl configuration file.");
        }
        String keyPasswordProperty = resolvePropertyName(mode, SSL_KEYSTORE_KEYPASSWORD_TPL_KEY);
        // Key password defaults to the same value as store password for
        // compatibility with legacy configurations that did not use a separate
        // configuration property for key password.
        String keystoreKeyPassword = getPassword(conf, keyPasswordProperty, keystorePassword);
        if (LOG.isDebugEnabled()) {
            LOG.debug(mode.toString() + " KeyStore: " + keystoreLocation);
        }

        long keyStoreReloadInterval = conf.getLong(
                resolvePropertyName(mode, SSL_KEYSTORE_RELOAD_INTERVAL_TPL_KEY),
                DEFAULT_SSL_KEYSTORE_RELOAD_INTERVAL);
        String timeUnitStr = conf.get(resolvePropertyName(mode, SSL_KEYSTORE_RELOAD_TIMEUNIT_TPL_KEY),
                DEFAULT_SSL_KEYSTORE_RELOAD_TIMEUNIT);
        TimeUnit reloadTimeUnit = TimeUnit.valueOf(timeUnitStr.toUpperCase());

        String passwordFileLocationProperty = resolvePropertyName(mode, SSL_PASSWORDFILE_LOCATION_TPL_KEY);
        String passwordFileLocation = conf.get(passwordFileLocationProperty, null);
        keyManager = new ReloadingX509KeyManager(keystoreType, keystoreLocation, keystorePassword,
                passwordFileLocation, keystoreKeyPassword, keyStoreReloadInterval, reloadTimeUnit);

        keyManager.init();
        if (LOG.isDebugEnabled()) {
            LOG.debug(mode.toString() + " Loaded KeyStore: " + keystoreLocation);
        }
        keyManagers = new KeyManager[] { keyManager };
    } else {
        // Deal with it
        KeyStore keyStore = KeyStore.getInstance(keystoreType);
        keyStore.load(null, null);
        KeyManagerFactory keyMgrFactory = KeyManagerFactory.getInstance(SSLFactory.SSLCERTIFICATE);
        keyMgrFactory.init(keyStore, null);
        keyManagers = keyMgrFactory.getKeyManagers();
    }
}