List of usage examples for java.security KeyStore getInstance
public static KeyStore getInstance(String type) throws KeyStoreException
From source file:com.wso2telco.gsma.shorten.BitlyUrlShorten.java
/** * Gets the new http client./* ww w .ja v a 2s .co m*/ * * @return the new http client */ @SuppressWarnings("deprecation") public CloseableHttpClient getNewHttpClient() { try { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); org.apache.http.conn.ssl.SSLSocketFactory sf = new SSLSocket(trustStore); sf.setHostnameVerifier(org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", sf, 443)); ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); return new DefaultHttpClient(ccm, params); } catch (Exception e) { return new DefaultHttpClient(); } }
From source file:com.netflix.client.ssl.URLSslContextFactory.java
/** * Opens the specified key or trust store using the given password. * * In case of failure {@link com.netflix.client.ssl.ClientSslSocketFactoryException} is thrown, and wrapps the * underlying cause exception. That could be: * <ul>// ww w . j av a2 s . c o m * <li>KeyStoreException if the JRE doesn't support the standard Java Keystore format, in other words: never</li> * <li>NoSuchAlgorithmException if the algorithm used to check the integrity of the keystore cannot be found</li> * <li>CertificateException if any of the certificates in the keystore could not be loaded</li> * <li> * IOException if there is an I/O or format problem with the keystore data, if a * password is required but not given, or if the given password was incorrect. If the * error is due to a wrong password, the cause of the IOException should be an UnrecoverableKeyException. * </li> * </ul> * * @param storeFile the location of the store to load * @param password the password protecting the store * @return the newly loaded key store * @throws ClientSslSocketFactoryException a wrapper exception for any problems encountered during keystore creation. */ private static KeyStore createKeyStore(final URL storeFile, final String password) throws ClientSslSocketFactoryException { if (storeFile == null) { return null; } Preconditions.checkArgument(StringUtils.isNotEmpty(password), "Null keystore should have empty password, defined keystore must have password"); KeyStore keyStore = null; try { keyStore = KeyStore.getInstance("jks"); InputStream is = storeFile.openStream(); try { keyStore.load(is, password.toCharArray()); } catch (NoSuchAlgorithmException e) { throw new ClientSslSocketFactoryException( String.format("Failed to create a keystore that supports algorithm %s: %s", SOCKET_ALGORITHM, e.getMessage()), e); } catch (CertificateException e) { throw new ClientSslSocketFactoryException(String.format( "Failed to create keystore with algorithm %s due to certificate exception: %s", SOCKET_ALGORITHM, e.getMessage()), e); } finally { try { is.close(); } catch (IOException ignore) { // NOPMD } } } catch (KeyStoreException e) { throw new ClientSslSocketFactoryException( String.format("KeyStore exception creating keystore: %s", e.getMessage()), e); } catch (IOException e) { throw new ClientSslSocketFactoryException( String.format("IO exception creating keystore: %s", e.getMessage()), e); } return keyStore; }
From source file:org.apache.axis2.transport.nhttp.HttpCoreNIOSSLListener.java
/** * Create the SSLContext to be used by this listener * @param transportIn the Axis2 transport description * @return the SSLContext to be used// w ww . ja v a 2 s. c o m */ protected SSLContext getSSLContext(TransportInDescription transportIn) throws AxisFault { KeyManager[] keymanagers = null; TrustManager[] trustManagers = null; Parameter keyParam = transportIn.getParameter("keystore"); Parameter trustParam = transportIn.getParameter("truststore"); if (keyParam != null) { OMElement ksEle = keyParam.getParameterElement().getFirstElement(); String location = ksEle.getFirstChildWithName(new QName("Location")).getText(); String type = ksEle.getFirstChildWithName(new QName("Type")).getText(); String storePassword = ksEle.getFirstChildWithName(new QName("Password")).getText(); String keyPassword = ksEle.getFirstChildWithName(new QName("KeyPassword")).getText(); try { KeyStore keyStore = KeyStore.getInstance(type); URL url = getClass().getClassLoader().getResource(location); log.debug("Loading Key Store from URL : " + url); keyStore.load(url.openStream(), storePassword.toCharArray()); KeyManagerFactory kmfactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmfactory.init(keyStore, keyPassword.toCharArray()); keymanagers = kmfactory.getKeyManagers(); } catch (GeneralSecurityException gse) { log.error("Error loading Key store : " + location, gse); throw new AxisFault("Error loading Key store : " + location, gse); } catch (IOException ioe) { log.error("Error opening Key store : " + location, ioe); throw new AxisFault("Error opening Key store : " + location, ioe); } } if (trustParam != null) { OMElement tsEle = trustParam.getParameterElement().getFirstElement(); String location = tsEle.getFirstChildWithName(new QName("Location")).getText(); String type = tsEle.getFirstChildWithName(new QName("Type")).getText(); String storePassword = tsEle.getFirstChildWithName(new QName("Password")).getText(); try { KeyStore trustStore = KeyStore.getInstance(type); URL url = getClass().getClassLoader().getResource(location); log.debug("Loading Trust Key Store from URL : " + url); trustStore.load(url.openStream(), storePassword.toCharArray()); TrustManagerFactory trustManagerfactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerfactory.init(trustStore); trustManagers = trustManagerfactory.getTrustManagers(); } catch (GeneralSecurityException gse) { log.error("Error loading Key store : " + location, gse); throw new AxisFault("Error loading Key store : " + location, gse); } catch (IOException ioe) { log.error("Error opening Key store : " + location, ioe); throw new AxisFault("Error opening Key store : " + location, ioe); } } try { SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(keymanagers, trustManagers, null); return sslcontext; } catch (GeneralSecurityException gse) { log.error("Unable to create SSL context with the given configuration", gse); throw new AxisFault("Unable to create SSL context with the given configuration", gse); } }
From source file:com.ntsync.android.sync.client.MyHttpClient.java
private SocketFactory getSSLSocketFactory() { InputStream in = null;/*from w w w . ja v a 2 s .co m*/ SocketFactory socketFack = null; try { KeyStore trusted = KeyStore.getInstance("BKS"); in = context.getResources().openRawResource(R.raw.mykeystore); trusted.load(in, "pwd23key".toCharArray()); SSLSocketFactory sslSocketFack = new SSLSocketFactory(trusted); socketFack = sslSocketFack; if (Constants.USE_RELEASE_CONFIG) { sslSocketFack.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); } else { Log.w(TAG, "Disable SSL Hostname verification"); sslSocketFack.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); } } catch (GeneralSecurityException e) { Log.e(TAG, "Loading truststore failed.", e); } catch (IOException e) { Log.e(TAG, "Loading truststore failed.", e); } finally { try { if (in != null) { in.close(); } } catch (IOException e) { Log.e(TAG, "closing filescocket failed.", e); } } if (socketFack == null) { Log.w(TAG, "Fallback to custom ssl socket factory."); socketFack = new MySSLSocketFactory(); } return socketFack; }
From source file:sample.tomcat.X509ApplicationTests.java
private SSLConnectionSocketFactory socketFactory() throws Exception { char[] password = "password".toCharArray(); KeyStore truststore = KeyStore.getInstance("PKCS12"); truststore.load(getKeyStoreFile(), password); SSLContextBuilder builder = new SSLContextBuilder(); builder.loadKeyMaterial(truststore, password); builder.loadTrustMaterial(truststore, new TrustSelfSignedStrategy()); return new SSLConnectionSocketFactory(builder.build(), new AllowAllHostnameVerifier()); }
From source file:be.fgov.kszbcss.rhq.websphere.connector.security.TrustStoreManager.java
private KeyStore loadTrustStore() throws GeneralSecurityException, IOException { Lock lock = truststoreLock.readLock(); lock.lock();/*from w w w . ja v a2s . co m*/ try { KeyStore truststore = KeyStore.getInstance("JKS"); if (truststoreFile.exists()) { if (log.isDebugEnabled()) { log.debug("Loading existing trust store from " + truststoreFile); } InputStream in = new FileInputStream(truststoreFile); try { truststore.load(in, new char[0]); } finally { in.close(); } if (log.isDebugEnabled()) { log.debug("Trust store has " + truststore.size() + " existing entries"); } } else { if (log.isDebugEnabled()) { log.debug("Trust store " + truststoreFile + " doesn't exist yet; a new one will be created if necessary"); } truststore.load(null); } return truststore; } finally { lock.unlock(); } }
From source file:org.metaeffekt.dcc.shell.RemoteAgentTest.java
private HttpClient newHttpClient() throws GeneralSecurityException, IOException { final char[] password = "DYKK8T8m9nKqBRPZ".toCharArray(); final KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(getClass().getResourceAsStream("/dcc-shell.keystore"), password); final KeyStore trustStore = KeyStore.getInstance("JKS"); trustStore.load(getClass().getResourceAsStream("/dcc-shell.truststore"), password); final SSLContextBuilder sslContextBuilder = SSLContexts.custom(); sslContextBuilder.loadKeyMaterial(keyStore, password); sslContextBuilder.loadTrustMaterial(trustStore); final HttpClientBuilder builder = HttpClientBuilder.create(); builder.setSslcontext(sslContextBuilder.build()); builder.setHostnameVerifier(new AllowAllHostnameVerifier()); final HttpClient client = builder.build(); return client; }
From source file:com.spotify.sshagenttls.CertHttpsHandler.java
public void handle(final HttpsURLConnection conn) { final CertKey certKey; try {/*from w ww.j av a 2s. c o m*/ certKey = createCertKey(); } catch (IOException | GeneralSecurityException e) { if (failOnCertError) { throw new RuntimeException(e); } else { LOG.warn("Error when setting up client certificates fromPaths {}. Error was '{}'. " + "No cert will be sent with request.", getCertSource(), e.toString()); LOG.debug("full exception fromPaths setting up ClientCertificate follows", e); return; } } final Certificate cert = certKey.cert(); final PrivateKey key = certKey.key(); // Generate a keystore password. // Do all this locally to not make copies of the password in memory. final SecureRandom random = new SecureRandom(); final int numBytes = 60; final char[] keyStorePassword = new char[numBytes]; for (int i = 0; i < numBytes; i++) { // Only use ASCII characters for the password. The corresponding integer range is [32, 126]. keyStorePassword[i] = (char) (random.nextInt(95) + 32); } try { // We're creating a keystore in memory and putting the cert & key into it. // The keystore needs a password when we put the key into it, even though it's only going to // exist for the lifetime of the process. So we just have some random password that we use. final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, null); keyStore.setCertificateEntry("client", cert); keyStore.setKeyEntry("key", key, keyStorePassword, new Certificate[] { cert }); // build an SSLContext based on our keystore, and then get an SSLSocketFactory fromPaths that final SSLContext sslContext = SSLContexts.custom().useProtocol("TLS") .loadKeyMaterial(keyStore, keyStorePassword).build(); // Clear out arrays that had password Arrays.fill(keyStorePassword, '\0'); conn.setSSLSocketFactory(sslContext.getSocketFactory()); } catch (CertificateException | IOException | NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException | KeyManagementException e) { // so many dumb ways to die. see https://www.youtube.com/watch?v=IJNR2EpS0jw for more. throw new RuntimeException(e); } }
From source file:org.springframework.cloud.vault.ClientHttpRequestFactoryFactory.java
private static KeyManagerFactory createKeyManagerFactory(Resource keystoreFile, String storePassword) throws GeneralSecurityException, IOException { KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); try (InputStream inputStream = keystoreFile.getInputStream()) { keyStore.load(inputStream, StringUtils.hasText(storePassword) ? storePassword.toCharArray() : null); }//from ww w . j a v a 2s . co m KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keyStore, StringUtils.hasText(storePassword) ? storePassword.toCharArray() : new char[0]); return keyManagerFactory; }
From source file:org.commonjava.indy.httprox.ProxyHttpsWildcardHostCertTest.java
private KeyStore getTrustStore(File jks) throws Exception { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); try (FileInputStream instream = new FileInputStream(jks)) { trustStore.load(instream, "passwd".toCharArray()); }/* ww w .j ava 2 s . c o m*/ return trustStore; }