List of usage examples for java.security KeyStore getDefaultType
public static final String getDefaultType()
From source file:com.rockagen.commons.http.HttpConn.java
/** * Handler main//w w w . ja v a 2 s . co m * * @param targetHost target {@link HttpHost} * @param proxyHost proxy {@link HttpHost} * @param httpRequestMethod HttpGet or HttpPost... * @param encoding encoding * @param upc {@link UsernamePasswordCredentials} * @param keystore keystore stream * @param password keystore password * @return result String * @throws IOException if an I/O error occurs */ protected static String execute(HttpHost targetHost, HttpHost proxyHost, HttpRequest httpRequestMethod, String encoding, UsernamePasswordCredentials upc, InputStream keystore, char[] password) throws IOException { HttpClientBuilder hcb = HttpClients.custom(); hcb.setDefaultRequestConfig(getRequestConfig()); if (proxyHost != null) { hcb.setProxy(proxyHost); } if (keystore != null) { try { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(keystore, password); SSLContext sslcontext = SSLContexts.custom() .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build(); SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(sslcontext); hcb.setSSLSocketFactory(ssf); } catch (KeyStoreException e) { log.error("{}", e.getMessage(), e); } catch (CertificateException e) { log.error("{}", e.getMessage(), e); } catch (NoSuchAlgorithmException e) { log.error("{}", e.getMessage(), e); } catch (KeyManagementException e) { log.error("{}", e.getMessage(), e); } finally { keystore.close(); } } if (upc != null) { CredentialsProvider cp = new BasicCredentialsProvider(); AuthScope as = new AuthScope(targetHost); cp.setCredentials(as, upc); hcb.setDefaultCredentialsProvider(cp); } CloseableHttpClient chc = hcb.build(); try { CloseableHttpResponse response = chc.execute(targetHost, httpRequestMethod); return getResponse(response, encoding); } finally { chc.close(); } }
From source file:net.geoprism.dashboard.DashboardMap.java
/** * Makes a getMap request to geoserver and returns the response as a ByteArrayOutputStream * //from w ww . j a v a2 s.c o m * @throws NoSuchAlgorithmException * * @requestURL = geoserver getMap() or getLegendGraphic() request url */ private byte[] requestGeoserverImage(String requestURL) { InputStream inStream = null; ByteArrayOutputStream outStream = null; CloseableHttpResponse response = null; CloseableHttpClient client = null; try { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); // StorePath and StorePass must be set for the systems keystore trustStore.load(new FileInputStream(GeoserverProperties.getGeoserverKeystorePath()), GeoserverProperties.getGeoserverKeystorePass().toCharArray()); SSLContext sslcontext = SSLContexts.custom() .loadKeyMaterial(trustStore, GeoserverProperties.getGeoserverKeystorePass().toCharArray()) .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build(); // // TODO: socket factory load once ever // SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); client = HttpClients.custom() // Allow all hostnames regardless of what is specified in the certificate .setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER) // Use the provided SSL socket factory .setSSLSocketFactory(factory) // Set a default cookie store which will be used in all of the requests .setDefaultCookieStore(new BasicCookieStore()).build(); HttpGet method = new HttpGet(requestURL); response = client.execute(method); inStream = response.getEntity().getContent(); outStream = new ByteArrayOutputStream(); // Copy the input stream to the output stream IOUtils.copy(inStream, outStream); } catch (MalformedURLException e) { String error = "The URL is not formated correctly."; throw new ProgrammingErrorException(error, e); } catch (IOException e) { String error = "Could not make the request to the map server."; throw new ProgrammingErrorException(error, e); } catch (KeyStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (KeyManagementException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (CertificateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnrecoverableKeyException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (inStream != null) { try { inStream.close(); } catch (IOException e) { String error = "Could not close stream."; throw new ProgrammingErrorException(error, e); } } if (outStream != null) { try { outStream.close(); } catch (IOException e) { String error = "Could not close stream."; throw new ProgrammingErrorException(error, e); } } if (response != null) { try { response.close(); } catch (IOException e) { String error = "Could not close stream."; throw new ProgrammingErrorException(error, e); } } if (client != null) { try { client.close(); } catch (IOException e) { String error = "Could not close stream."; throw new ProgrammingErrorException(error, e); } } } return outStream.toByteArray(); }
From source file:io.hops.hopsworks.common.project.ProjectController.java
private void killZeppelin(Integer projectId, String sessionId) throws ServiceException { Client client;/*from ww w .j av a2 s . c om*/ Response resp; try (FileInputStream trustStoreIS = new FileInputStream(settings.getGlassfishTrustStore())) { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(trustStoreIS, null); client = ClientBuilder.newBuilder().trustStore(trustStore) .hostnameVerifier(InsecureHostnameVerifier.INSTANCE).build(); resp = client.target(settings.getRestEndpoint()) .path("/hopsworks-api/api/zeppelin/" + projectId + "/interpreter/check").request() .cookie("SESSION", sessionId).method("GET"); LOGGER.log(Level.FINE, "Zeppelin check resp:{0}", resp.getStatus()); } catch (CertificateException | NoSuchAlgorithmException | IOException | KeyStoreException e) { throw new ServiceException(RESTCodes.ServiceErrorCode.ZEPPELIN_KILL_ERROR, Level.SEVERE, null, e.getMessage(), e); } if (resp.getStatus() == 200) { resp = client.target(settings.getRestEndpoint() + "/hopsworks-api/api/zeppelin/" + projectId + "/interpreter/restart").request().cookie("SESSION", sessionId).method("GET"); LOGGER.log(Level.FINE, "Zeppelin restart resp:{0}", resp.getStatus()); if (resp.getStatus() != 200) { throw new ServiceException(RESTCodes.ServiceErrorCode.ZEPPELIN_KILL_ERROR, Level.SEVERE); } } }
From source file:com.verisign.epp.codec.launch.EPPLaunchTst.java
/** * Loads the trust store file and the Certificate Revocation List (CRL) file * into the <code>PKIXParameters</code> used to verify the certificate chain * and verify the certificate against the CRL. Both the Java Trust Store is * loaded with the trusted root CA certificates (trust anchors) and the CRL * file is attempted to be loaded to identify the revoked certificates. If * the CRL file is not found, then no CRL checking will be done. * //ww w .j a v a 2 s . c om * @param aTrustStoreName * Trust store file name * @param aCrls * List of Certificate Revocation List (CRL) file names * * @return Initialized <code>PKIXParameters</code> instance. * * @throws Exception * Error initializing the PKIX parameters */ public static PKIXParameters loadPKIXParameters(String aTrustStoreName, List<String> aCrls) throws Exception { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream trustStoreFile = new FileInputStream(aTrustStoreName); trustStore.load(trustStoreFile, null); PKIXParameters pkixParameters = new PKIXParameters(trustStore); CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); Collection crlContentsList = new ArrayList(); for (String currCrl : aCrls) { File crlFile = new File(currCrl); if (crlFile.exists()) { InputStream inStream = null; try { inStream = new FileInputStream(currCrl); crlContentsList.add(certFactory.generateCRL(inStream)); } finally { if (inStream != null) { inStream.close(); } } } else { System.err.println("CRL file \"" + currCrl + "\" NOT found."); } } // At least 1 CRL was loaded if (crlContentsList.size() != 0) { List<CertStore> certStores = new ArrayList<CertStore>(); certStores.add(CertStore.getInstance("Collection", new CollectionCertStoreParameters(crlContentsList))); pkixParameters.setCertStores(certStores); pkixParameters.setRevocationEnabled(true); System.out.println("Revocation enabled"); } else { pkixParameters.setRevocationEnabled(false); System.out.println("Revocation disabled."); } return pkixParameters; }
From source file:com.verisign.epp.codec.launch.EPPLaunchTst.java
/** * Loads the private key used to digitally sign from a Java KeyStore with * the alias of the <code>PrivateKeyEntry</code> and the password to access * the Keystore and the key.// w ww. j av a 2 s. c o m * * @param aKeyStoreName * Java Keystore to load the key from * @param aKeyAliasName * Java Keystore alias of key * @param aPassword * Password to access Java Keystore and key * * @return Loaded <code>KeyStore.PrivateKeyEntry</code> that can be used to * get the private key and it's associated certificate chain. * * @throws Exception * Error loading private key */ private static KeyStore.PrivateKeyEntry loadPrivateKeyEntry(String aKeyStoreName, String aKeyAliasName, String aPassword) throws Exception { // Load KeyStore KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream keyStoreFile = new FileInputStream(aKeyStoreName); keyStore.load(keyStoreFile, aPassword.toCharArray()); // Get Private Key assert keyStore.isKeyEntry(aKeyAliasName); KeyStore.PrivateKeyEntry keyEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(aKeyAliasName, new KeyStore.PasswordProtection(aPassword.toCharArray())); return keyEntry; }
From source file:com.verisign.epp.codec.launch.EPPLaunchTst.java
/** * Loads the public key used to verify a digital signature signed with the * associated private key, loaded by/*from ww w . ja va 2 s . c om*/ * {@link #loadPrivateKeyEntry(String, String, String)}. * * @param aKeyStoreName * Java Keystore containing the certificate * @param aPublicKeyAlias * Java Keystore alias of the <code>trustedCertEntry</code> * containing the public key * * @return Loaded <code>PublicKey</code> instance * * @throws Exception * Error loading the public key */ public static PublicKey loadPublicKey(String aKeyStoreName, String aPublicKeyAlias) throws Exception { // Load KeyStore KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream keyStoreFile = new FileInputStream(aKeyStoreName); keyStore.load(keyStoreFile, null); assert keyStore.isCertificateEntry(aPublicKeyAlias); KeyStore.TrustedCertificateEntry certEntry = (KeyStore.TrustedCertificateEntry) keyStore .getEntry(aPublicKeyAlias, null); return certEntry.getTrustedCertificate().getPublicKey(); }
From source file:com.gft.unity.android.AndroidIO.java
public void createHttpClients() throws NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException, KeyManagementException, UnrecoverableKeyException { SSLSocketFactory socketFactory; SchemeRegistry registry = new SchemeRegistry(); LOG.LogDebug(Module.PLATFORM, "Certificate Validation Enabled = " + this.Validatecertificates()); if (this.Validatecertificates()) { HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; // Set verifier HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier); /******************************** * USING DEFAULT ANDROID DEVICE SSLSocketFactory * the default factory was throwing errors verifying ssl certificates chains for some specific CA Authorities * (for example, Verisign root ceritificate G5 is not available on android devices <=2.3) * See more details on jira ticket [MOBPLAT-63] ******************************** SSLSocketFactory socketFactory = SSLSocketFactory .getSocketFactory();// ww w . j a v a2s . c o m socketFactory .setHostnameVerifier((X509HostnameVerifier) hostnameVerifier); */ /* /******************************** * USING VALIDATING SSLSocketFactory - Validating certificates per demand * See more details on jira ticket [MOBPLAT-63] ******************************** */ KeyStore trustStore; if (Build.VERSION.SDK_INT >= 14) { trustStore = KeyStore.getInstance("AndroidCAStore"); trustStore.load(null, null); } else { try { trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); ; String filename = "/system/etc/security/cacerts.bks".replace('/', File.separatorChar); FileInputStream is = new FileInputStream(filename); trustStore.load(is, "changeit".toCharArray()); is.close(); } catch (Exception ex) { try { /* /******************************** * HTC 2.3.5 Access Keystore problem * See more details on jira ticket [MOBPLAT-91] ******************************** */ trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); String filename = "/system/etc/security/cacerts.bks".replace('/', File.separatorChar); FileInputStream is = new FileInputStream(filename); trustStore.load(is, null); is.close(); } catch (Exception e) { trustStore = null; LOG.Log(Module.PLATFORM, "A problem has been detected while accessing the device keystore.", e); } } } socketFactory = ValidatingSSLSocketFactory.GetInstance(trustStore); socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier); LOG.LogDebug(Module.PLATFORM, "Using ValidatingSSLSocketFactory (custom socket Factory)"); } else { /* * ******************************* * USING CUSTOM SSLSocketFactory - accept all certificates * See more details on jira ticket [MOBPLAT-63] ******************************** */ KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); socketFactory = new MySSLSocketFactory(trustStore); LOG.LogDebug(Module.PLATFORM, "Using MySSLSocketFactory (custom socket factory - accepting all certificates)"); } registry.register(new Scheme("https", socketFactory, 443)); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); ThreadSafeClientConnManager mgr = new ThreadSafeClientConnManager(new DefaultHttpClient().getParams(), registry); httpSSLClient = new DefaultHttpClient(mgr, new DefaultHttpClient().getParams()); // [MOBPLAT-200] : allow gzip, deflate decompression modes httpSSLClient.addResponseInterceptor(new GzipHttpResponseInterceptor()); LOG.LogDebug(Module.PLATFORM, "httpSSLClient stored for next HTTPS access"); }
From source file:com.vmware.identity.idm.client.TenantManagementTest.java
private KeyStore loadKeyStore(String keyStoreNameInfo, String passwordIfno) { try {/*from ww w .j a v a 2s .c o m*/ Properties props = getTestProperties(); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); String password = props.getProperty(passwordIfno); Assert.assertNotNull(password); String keyStoreResourceName = props.getProperty(keyStoreNameInfo); Assert.assertNotNull(keyStoreResourceName); ks.load(getClass().getResourceAsStream(keyStoreResourceName), password.toCharArray()); return ks; } catch (Exception e) { throw new IllegalStateException(e); } }