Example usage for java.security KeyStore getDefaultType

List of usage examples for java.security KeyStore getDefaultType

Introduction

In this page you can find the example usage for java.security KeyStore getDefaultType.

Prototype

public static final String getDefaultType() 

Source Link

Document

Returns the default keystore type as specified by the keystore.type security property, or the string "jks" (acronym for "Java keystore" ) if no such property exists.

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 {// ww w .  j  ava  2s  .co  m
            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.hyperledger.fabric.sdk.security.CryptoPrimitivesTest.java

@Test
public void testAddCACertificateToTrustStoreBadStore() throws Exception {

    thrown.expect(CryptoException.class);
    thrown.expectMessage("Unable to add");

    // Create an uninitialized key store
    KeyStore tmpKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());

    // Ensure that crypto is using that store
    KeyStore saveKeyStore = (KeyStore) setField(crypto, "trustStore", tmpKeyStore);

    try {//from ww w . j av a  2  s .  c  o  m
        crypto.addCACertificateToTrustStore(testCACert, "alias");
    } finally {
        // Ensure we set it back so that subsequent tests will not be affected
        setField(crypto, "trustStore", saveKeyStore);
    }
}

From source file:org.springframework.boot.web.servlet.server.AbstractServletWebServerFactoryTests.java

@Test
public void sslWantsClientAuthenticationSucceedsWithClientCertificate() throws Exception {
    AbstractServletWebServerFactory factory = getFactory();
    addTestTxtFile(factory);/*from  ww  w.j a  va  2 s.c  o m*/
    factory.setSsl(getSsl(ClientAuth.WANT, "password", "classpath:test.jks"));
    this.webServer = factory.getWebServer();
    this.webServer.start();
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(new FileInputStream(new File("src/test/resources/test.jks")), "secret".toCharArray());
    SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
            new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy())
                    .loadKeyMaterial(keyStore, "password".toCharArray()).build());
    HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(
            httpClient);
    assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)).isEqualTo("test");
}

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

@Test
public void testRfc3163Example() throws Exception {
    // This test uses the example from page 10 in RFC 3163 (https://tools.ietf.org/html/rfc3163#section-5)
    mockRandom(new byte[] { 18, 56, -105, 88, 121, -121, 71, -104 });

    KeyStore emptyTrustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    emptyTrustStore.load(null, null);/*from  ww w .  ja  v a2  s .  c om*/
    final SaslServer saslServer = createSaslServer(SaslMechanismInformation.Names.IEC_ISO_9798_U_RSA_SHA1_ENC,
            "", getX509KeyManager(serverKeyStore, KEYSTORE_PASSWORD), emptyTrustStore);
    assertNotNull(saslServer);
    assertFalse(saslServer.isComplete());

    byte[] tokenBA1 = saslServer.evaluateResponse(new byte[0]);
    byte[] expectedTokenBA1 = CodePointIterator.ofString("MAoECBI4l1h5h0eY").base64Decode().drain();
    assertArrayEquals(expectedTokenBA1, tokenBA1);
    assertFalse(saslServer.isComplete());

    byte[] tokenAB = CodePointIterator.ofString(
            "MIIBAgQIIxh5I0h5RYegD4INc2FzbC1yLXVzLmNvbaFPFk1odHRwOi8vY2VydHMtci11cy5jb20vY2VydD9paD1odmNOQVFFRkJRQURnWUVBZ2hBR2hZVFJna0ZqJnNuPUVQOXVFbFkzS0RlZ2pscjCBkzANBgkqhkiG9w0BAQUFAAOBgQCkuC2GgtYcxGG1NEzLA4bh5lqJGOZySACMmc+mDrV7A7KAgbpO2OuZpMCl7zvNt/L3OjQZatiX8d1XbuQ40l+g2TJzJt06o7ogomxdDwqlA/3zp2WMohlI0MotHmfDSWEDZmEYDEA3/eGgkWyi1v1lEVdFuYmrTr8E4wE9hxdQrA==")
            .base64Decode().drain();
    try {
        saslServer.evaluateResponse(tokenAB);
        fail("Expected SaslException not thrown");
    } catch (SaslException expected) {
        // The example specifies the client's certificate using a fake URL (http://certs-r-us.com/cert?ih=hvcNAQEFBQADgYEAghAGhYTRgkFj&sn=EP9uElY3KDegjlr)
        // so we can actually make use of it.
        assertTrue(expected.getCause().getMessage().contains("certificate"));
    }
    assertFalse(saslServer.isComplete());
}

From source file:org.elasticsearch.xpack.core.ssl.SSLConfigurationReloaderTests.java

private static MockWebServer getSslServer(Path keyStorePath, String keyStorePass)
        throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException,
        KeyManagementException, UnrecoverableKeyException {
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    try (InputStream is = Files.newInputStream(keyStorePath)) {
        keyStore.load(is, keyStorePass.toCharArray());
    }/*from w  w  w.j  a v  a2s .co m*/
    final SSLContext sslContext = new SSLContextBuilder().loadKeyMaterial(keyStore, keyStorePass.toCharArray())
            .build();
    MockWebServer server = new MockWebServer(sslContext, false);
    server.enqueue(new MockResponse().setResponseCode(200).setBody("body"));
    server.start();
    return server;
}

From source file:org.elasticsearch.xpack.core.ssl.SSLConfigurationReloaderTests.java

private static CloseableHttpClient getSSLClient(Path trustStorePath, String trustStorePass)
        throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException, IOException,
        CertificateException {/* ww w .  java2s  .  c  o  m*/
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    try (InputStream is = Files.newInputStream(trustStorePath)) {
        trustStore.load(is, trustStorePass.toCharArray());
    }
    final SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(trustStore, null).build();
    return HttpClients.custom().setSSLContext(sslContext).build();
}

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

/**
 * This sets the trust managers that will be used for all TLS and SSL connections to the ldap. This method will
 * remove any cached results and initialize the connection manager.
 * //ww w .  j ava 2  s  .c o  m
 * @see #clearCache()
 * @see #setSslSocketFactory(SSLSocketFactory)
 * 
 * @param tc <code>X509Credential</code> to create TrustManagers with
 */
public void setSslTrustManagers(X509Credential tc) {
    if (tc != null) {
        try {
            TrustManagerFactory tmf = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
            keystore.load(null, null);
            for (X509Certificate c : tc.getEntityCertificateChain()) {
                keystore.setCertificateEntry("ldap_tls_trust_" + c.getSerialNumber(), c);
            }
            tmf.init(keystore);
            sslTrustManagers = tmf.getTrustManagers();
        } catch (GeneralSecurityException e) {
            log.error("Error initializing trust managers", e);
        } catch (IOException e) {
            log.error("Error initializing trust managers", e);
        }
    }
}

From source file:org.apache.zeppelin.livy.BaseLivyInterpreter.java

private RestTemplate createRestTemplate() {
    String keytabLocation = getProperty("zeppelin.livy.keytab");
    String principal = getProperty("zeppelin.livy.principal");
    boolean isSpnegoEnabled = StringUtils.isNotEmpty(keytabLocation) && StringUtils.isNotEmpty(principal);

    HttpClient httpClient = null;//from   ww w. j a va  2  s . c om
    if (livyURL.startsWith("https:")) {
        String keystoreFile = getProperty("zeppelin.livy.ssl.trustStore");
        String password = getProperty("zeppelin.livy.ssl.trustStorePassword");
        if (StringUtils.isBlank(keystoreFile)) {
            throw new RuntimeException("No zeppelin.livy.ssl.trustStore specified for livy ssl");
        }
        if (StringUtils.isBlank(password)) {
            throw new RuntimeException("No zeppelin.livy.ssl.trustStorePassword specified " + "for livy ssl");
        }
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(keystoreFile);
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(new FileInputStream(keystoreFile), password.toCharArray());
            SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(trustStore).build();
            SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
            HttpClientBuilder httpClientBuilder = HttpClients.custom().setSSLSocketFactory(csf);
            RequestConfig reqConfig = new RequestConfig() {
                @Override
                public boolean isAuthenticationEnabled() {
                    return true;
                }
            };
            httpClientBuilder.setDefaultRequestConfig(reqConfig);
            Credentials credentials = new Credentials() {
                @Override
                public String getPassword() {
                    return null;
                }

                @Override
                public Principal getUserPrincipal() {
                    return null;
                }
            };
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(AuthScope.ANY, credentials);
            httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
            if (isSpnegoEnabled) {
                Registry<AuthSchemeProvider> authSchemeProviderRegistry = RegistryBuilder
                        .<AuthSchemeProvider>create().register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory())
                        .build();
                httpClientBuilder.setDefaultAuthSchemeRegistry(authSchemeProviderRegistry);
            }

            httpClient = httpClientBuilder.build();
        } catch (Exception e) {
            throw new RuntimeException("Failed to create SSL HttpClient", e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    LOGGER.error("Failed to close keystore file", e);
                }
            }
        }
    }

    RestTemplate restTemplate = null;
    if (isSpnegoEnabled) {
        if (httpClient == null) {
            restTemplate = new KerberosRestTemplate(keytabLocation, principal);
        } else {
            restTemplate = new KerberosRestTemplate(keytabLocation, principal, httpClient);
        }
    } else {
        if (httpClient == null) {
            restTemplate = new RestTemplate();
        } else {
            restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));
        }
    }
    restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
    return restTemplate;
}

From source file:com.photon.phresco.framework.rest.api.util.FrameworkServiceUtil.java

public static List<CertificateInfo> getCertificate(String host, int port) throws PhrescoException {
    List<CertificateInfo> certificates = new ArrayList<CertificateInfo>();
    CertificateInfo info;//  w  w w.j  a  v  a  2  s . co  m
    try {
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        SSLContext context = SSLContext.getInstance("TLS");
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ks);
        X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
        SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
        context.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory factory = context.getSocketFactory();
        SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
        socket.setSoTimeout(10000);
        try {
            socket.startHandshake();
            socket.close();
        } catch (SSLException e) {

        }
        X509Certificate[] chain = tm.chain;
        for (int i = 0; i < chain.length; i++) {
            X509Certificate x509Certificate = chain[i];
            String subjectDN = x509Certificate.getSubjectDN().getName();
            String[] split = subjectDN.split(",");
            info = new CertificateInfo();
            info.setSubjectDN(subjectDN);
            info.setDisplayName(split[0]);
            info.setCertificate(x509Certificate);
            certificates.add(info);
        }
    } catch (Exception e) {
        throw new PhrescoException(e);
    }
    return certificates;
}

From source file:org.springframework.boot.web.servlet.server.AbstractServletWebServerFactoryTests.java

@Test
public void sslWithCustomSslStoreProvider() throws Exception {
    AbstractServletWebServerFactory factory = getFactory();
    addTestTxtFile(factory);/*from  ww  w .  j  a v  a  2s  .  co  m*/
    Ssl ssl = new Ssl();
    ssl.setClientAuth(ClientAuth.NEED);
    ssl.setKeyPassword("password");
    factory.setSsl(ssl);
    SslStoreProvider sslStoreProvider = mock(SslStoreProvider.class);
    given(sslStoreProvider.getKeyStore()).willReturn(loadStore());
    given(sslStoreProvider.getTrustStore()).willReturn(loadStore());
    factory.setSslStoreProvider(sslStoreProvider);
    this.webServer = factory.getWebServer();
    this.webServer.start();
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(new FileInputStream(new File("src/test/resources/test.jks")), "secret".toCharArray());
    SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
            new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy())
                    .loadKeyMaterial(keyStore, "password".toCharArray()).build());
    HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(
            httpClient);
    assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)).isEqualTo("test");
    verify(sslStoreProvider).getKeyStore();
    verify(sslStoreProvider).getTrustStore();
}