Example usage for javax.net.ssl KeyManagerFactory getDefaultAlgorithm

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

Introduction

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

Prototype

public static final String getDefaultAlgorithm() 

Source Link

Document

Obtains the default KeyManagerFactory algorithm name.

Usage

From source file:it.danja.newsmonitor.utils.HttpServer.java

public void init() {

    // Set up the HTTP protocol processor
    HttpProcessor httpproc = HttpProcessorBuilder.create().add(new ResponseDate())
            .add(new ResponseServer("Test/1.1")).add(new ResponseContent()).add(new ResponseConnControl())
            .build();// w  w w. j ava  2s.  co m

    // Set up request handlers
    UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper();
    reqistry.register("*", new HttpFileHandler(docRoot));

    // Set up the HTTP service
    httpService = new HttpService(httpproc, reqistry);

    if (port == 8443) {
        // Initialize SSL context
        ClassLoader cl = HttpServer.class.getClassLoader();
        URL url = cl.getResource("my.keystore");
        if (url == null) {
            log.info("HttpServer : Keystore not found");
            System.exit(1);
        }
        KeyStore keystore = null;
        try {
            keystore = KeyStore.getInstance("jks");
        } catch (KeyStoreException e) {

            log.error(e.getMessage());
        }
        try {
            keystore.load(url.openStream(), "secret".toCharArray());
        } catch (NoSuchAlgorithmException e) {

            log.error(e.getMessage());
        } catch (CertificateException e) {

            log.error(e.getMessage());
        } catch (IOException e) {

            log.error(e.getMessage());
        }
        KeyManagerFactory kmfactory = null;
        try {
            kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        } catch (NoSuchAlgorithmException e) {

            log.error(e.getMessage());
        }
        try {
            kmfactory.init(keystore, "secret".toCharArray());
        } catch (UnrecoverableKeyException e) {

            log.error(e.getMessage());
        } catch (KeyStoreException e) {

            log.error(e.getMessage());
        } catch (NoSuchAlgorithmException e) {

            log.error(e.getMessage());
        }
        KeyManager[] keymanagers = kmfactory.getKeyManagers();
        SSLContext sslcontext = null;
        try {
            sslcontext = SSLContext.getInstance("TLS");
        } catch (NoSuchAlgorithmException e) {

            log.error(e.getMessage());
        }
        try {
            sslcontext.init(keymanagers, null, null);
        } catch (KeyManagementException e) {

            log.error(e.getMessage());
        }
        this.sf = sslcontext.getServerSocketFactory();
    }
}

From source file:org.elasticsearch.xpack.ssl.SSLClientAuthTests.java

private SSLContext getSSLContext() {
    try (InputStream in = Files.newInputStream(
            getDataPath("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testclient.jks"))) {
        KeyStore keyStore = KeyStore.getInstance("jks");
        keyStore.load(in, "testclient".toCharArray());
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(keyStore);/*from  w  w w .  j a  v a2  s . c  o m*/
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(keyStore, "testclient".toCharArray());
        SSLContext context = SSLContext.getInstance("TLSv1.2");
        context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
        return context;
    } catch (Exception e) {
        throw new ElasticsearchException("failed to initialize a TrustManagerFactory", e);
    }
}

From source file:it.anyplace.sync.core.security.KeystoreHandler.java

public KeyManager[] getKeyManagers()
        throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, KEY_PASSWORD.toCharArray());
    return keyManagerFactory.getKeyManagers();
}

From source file:edu.vt.middleware.ldap.LdapTLSSocketFactory.java

/**
 * This attempts to load the KeyManagers from the supplied <code>
 * InputStream</code> using the supplied password.
 *
 * @param  is  <code>InputStream</code> containing the keystore
 * @param  password  <code>String</code> to unlock the keystore
 * @param  storeType  <code>String</code> of keystore
 *
 * @return  <code>KeyManager[]</code>
 *
 * @throws  IOException  if the keystore cannot be loaded
 * @throws  GeneralSecurityException  if an errors occurs while loading the
 * KeyManagers/*from  w  w  w  .j a  v  a 2 s .c o  m*/
 */
private KeyManager[] initKeyManager(final InputStream is, final String password, final String storeType)
        throws IOException, GeneralSecurityException {
    KeyManager[] km = null;
    if (is != null) {
        final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(this.loadKeyStore(is, password, storeType), password != null ? password.toCharArray() : null);
        km = kmf.getKeyManagers();
    }
    return km;
}

From source file:com.thejoshwa.ultrasonic.androidapp.service.ssl.SSLSocketFactory.java

private static SSLContext createSSLContext(String algorithm, final KeyStore keystore,
        final String keystorePassword, final KeyStore truststore, final SecureRandom random,
        final TrustStrategy trustStrategy)
        throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, KeyManagementException {
    if (algorithm == null) {
        algorithm = TLS;/* w  w  w  .  j av  a2s  .c  o m*/
    }
    KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmfactory.init(keystore, keystorePassword != null ? keystorePassword.toCharArray() : null);
    KeyManager[] keymanagers = kmfactory.getKeyManagers();
    TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmfactory.init(keystore);
    TrustManager[] trustmanagers = tmfactory.getTrustManagers();
    if (trustmanagers != null && trustStrategy != null) {
        for (int i = 0; i < trustmanagers.length; i++) {
            TrustManager tm = trustmanagers[i];
            if (tm instanceof X509TrustManager) {
                trustmanagers[i] = new TrustManagerDecorator((X509TrustManager) tm, trustStrategy);
            }
        }
    }

    SSLContext sslcontext = SSLContext.getInstance(algorithm);
    sslcontext.init(keymanagers, trustmanagers, random);
    return sslcontext;
}

From source file:com.clustercontrol.plugin.impl.WebServicePlugin.java

/**
 * ???WebService?Agent????????//from w w w  .ja  v a 2 s. c om
 * @param addressPrefix ? http://x.x.x.x:xxxx? ?
 * @param addressBody ??? addressPrefix ??
 * @param endpointInstance
 * @param threadPool ?
 */
protected void publish(String addressPrefix, String addressBody, Object endpointInstance,
        ThreadPoolExecutor threadPool) {

    try {
        final URL urlPrefix = new URL(addressPrefix);
        final String fulladdress = addressPrefix + addressBody;
        HttpsServer httpsServer = null;
        // ? HTTPS???????HttpsService???endpoit.publish?????
        // URL??????????HttpsService?????Hashmap???????HashMap?
        // HTTPSServer???????????
        if ("https".equals(urlPrefix.getProtocol())) {
            httpsServer = httpsServerMap.get(addressPrefix);
            if (httpsServer == null) {
                // HTTPS Server??HTTPS?????????????????????
                String protocol = HinemosPropertyUtil.getHinemosPropertyStr("ws.https.protocol", "TLS");
                String keystorePath = HinemosPropertyUtil.getHinemosPropertyStr("ws.https.keystore.path",
                        HinemosPropertyDefault
                                .getString(HinemosPropertyDefault.StringKey.WS_HTTPS_KEYSTORE_PATH));
                String keystorePassword = HinemosPropertyUtil
                        .getHinemosPropertyStr("ws.https.keystore.password", "hinemos");
                String keystoreType = HinemosPropertyUtil.getHinemosPropertyStr("ws.https.keystore.type",
                        "PKCS12");
                log.info("Starting HTTPS Server...");
                log.info("SSLContext: " + protocol + ", KeyStore: " + keystoreType);
                SSLContext ssl = SSLContext.getInstance(protocol);
                KeyManagerFactory keyFactory = KeyManagerFactory
                        .getInstance(KeyManagerFactory.getDefaultAlgorithm());
                KeyStore store = KeyStore.getInstance(keystoreType);
                try (InputStream in = new FileInputStream(keystorePath)) {
                    store.load(in, keystorePassword.toCharArray());
                }
                keyFactory.init(store, keystorePassword.toCharArray());
                TrustManagerFactory trustFactory = TrustManagerFactory
                        .getInstance(TrustManagerFactory.getDefaultAlgorithm());
                trustFactory.init(store);
                ssl.init(keyFactory.getKeyManagers(), trustFactory.getTrustManagers(), new SecureRandom());
                HttpsConfigurator configurator = new HttpsConfigurator(ssl);

                // ??HTTPSSever???Hashmap??
                httpsServer = HttpsServer
                        .create(new InetSocketAddress(urlPrefix.getHost(), urlPrefix.getPort()), 0);
                httpsServer.setHttpsConfigurator(configurator);
                httpsServerMap.put(addressPrefix, httpsServer);
            }
        }

        // ?????endpoint??
        log.info("publish " + fulladdress);
        final Endpoint endpoint = Endpoint.create(endpointInstance);
        endpoint.setExecutor(threadPool);
        if (httpsServer != null) {
            endpoint.publish(httpsServer.createContext(addressBody));
        } else {
            endpoint.publish(fulladdress);
        }
        endpointList.add(endpoint);
    } catch (NoSuchAlgorithmException | UnrecoverableKeyException | KeyStoreException | KeyManagementException
            | IOException | CertificateException | RuntimeException e) {
        log.warn("failed to publish : " + e.getClass().getSimpleName() + ", " + e.getMessage(), e);
    } finally {

    }
}

From source file:org.wso2.carbon.inbound.ibmmq.poll.IbmMqConsumer.java

public void sslConnection() {
    String keyStoreLocation = properties.getProperty(ibmMqConstant.SSL_KEYSTORE_LOCATION);
    String keyStoreType = properties.getProperty(ibmMqConstant.SSL_KEYSTORE_TYPE);
    String keyStorePassword = properties.getProperty(ibmMqConstant.SSL_KEYSTORE_PASSWORD);
    String trustStoreLocation = properties.getProperty(ibmMqConstant.SSL_TRUSTSTORE_LOCATION);
    String trustStoreType = properties.getProperty(ibmMqConstant.SSL_TRUSTSTORE_TYPE);
    String sslVersion = properties.getProperty(ibmMqConstant.SSL_VERSION);
    String sslFipsRequired = properties.getProperty(ibmMqConstant.SSL_FIPS);
    String sslCipherSuite = properties.getProperty(ibmMqConstant.SSL_CIPHERSUITE);
    boolean sslFips = Boolean.parseBoolean(sslFipsRequired);
    try {/*w w w.j  a va  2 s. c  o m*/
        char[] keyPassphrase = keyStorePassword.toCharArray();
        KeyStore ks = KeyStore.getInstance(keyStoreType);
        ks.load(new FileInputStream(keyStoreLocation), keyPassphrase);
        KeyStore trustStore = KeyStore.getInstance(trustStoreType);
        trustStore.load(new FileInputStream(trustStoreLocation), null);

        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());

        trustManagerFactory.init(trustStore);
        keyManagerFactory.init(ks, keyPassphrase);
        SSLContext sslContext = SSLContext.getInstance(sslVersion);
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
        MQEnvironment.sslSocketFactory = sslContext.getSocketFactory();
        MQEnvironment.sslFipsRequired = sslFips;
        MQEnvironment.sslCipherSuite = sslCipherSuite;
    } catch (Exception ex) {
        handleException(ex.getMessage());
    }
}

From source file:org.jenkinsci.remoting.protocol.ProtocolStackLoopbackLoadStress.java

public ProtocolStackLoopbackLoadStress(boolean nio, boolean ssl)
        throws IOException, NoSuchAlgorithmException, CertificateException, KeyStoreException,
        UnrecoverableKeyException, KeyManagementException, OperatorCreationException {
    KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
    gen.initialize(2048); // maximum supported by JVM with export restrictions
    keyPair = gen.generateKeyPair();//from w w w.ja  va  2 s.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 PublicKeyMatchingX509ExtendedTrustManager(keyPair.getPublic()) }, null);

    hub = IOHub.create(executorService);
    serverSocketChannel = ServerSocketChannel.open();
    acceptor = new Acceptor(serverSocketChannel, nio, ssl);
}