List of usage examples for javax.net.ssl KeyManagerFactory getInstance
public static final KeyManagerFactory getInstance(String algorithm) throws NoSuchAlgorithmException
KeyManagerFactory
object that acts as a factory for key managers. From source file:org.nectarframework.base.service.nanohttp.NanoHttpService.java
/** * Creates an SSLSocketFactory for HTTPS. Pass a KeyStore resource with your * certificate and passphrase/*from w w w . ja v a 2 s . com*/ */ public ServerSocket makeSSLServerSocket(String keyAndTrustStoreClasspathPath, char[] passphrase) throws IOException { try { KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); InputStream keystoreStream = new FileInputStream(new File(keyAndTrustStoreClasspathPath)); keystore.load(keystoreStream, passphrase); KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keystore, passphrase); SSLServerSocketFactory res = null; try { TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keystore); SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null); res = ctx.getServerSocketFactory(); } catch (Exception e) { throw new IOException(e.getMessage()); } SSLServerSocket ss = null; ss = (SSLServerSocket) res.createServerSocket(); ss.setEnabledProtocols(ss.getSupportedProtocols()); ss.setUseClientMode(false); ss.setWantClientAuth(false); ss.setNeedClientAuth(false); return ss; } catch (Exception e) { throw new IOException(e.getMessage()); } }
From source file:android.core.SSLSocketTest.java
/** * Regression test for 963650: javax.net.ssl.KeyManager has no implemented * (documented?) algorithms./*from w w w . j a v a2s. c o m*/ */ public void testDefaultAlgorithms() throws Exception { SSLContext ctx = SSLContext.getInstance("TLS"); KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509"); KeyStore ks = KeyStore.getInstance("BKS"); assertEquals("X509", kmf.getAlgorithm()); assertEquals("X509", KeyManagerFactory.getDefaultAlgorithm()); assertEquals("BKS", ks.getType()); assertEquals("BKS", KeyStore.getDefaultType()); }
From source file:org.eclipse.emf.emfstore.client.model.connectionmanager.KeyStoreManager.java
/** * Returns a SSL Context. This is need for encryption, used by the * SSLSocketFactory./* w w w . j ava 2 s . c o m*/ * * @return SSL Context * @throws CertificateStoreException * in case of failure retrieving the context */ public SSLContext getSSLContext() throws CertificateStoreException { try { loadKeyStore(); KeyManagerFactory managerFactory = KeyManagerFactory.getInstance("SunX509"); managerFactory.init(keyStore, KEYSTOREPASSWORD.toCharArray()); TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509"); trustManagerFactory.init(keyStore); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(managerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null); HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }); return sslContext; } catch (NoSuchAlgorithmException e) { throw new CertificateStoreException("Loading certificate failed!", e); } catch (UnrecoverableKeyException e) { throw new CertificateStoreException("Loading certificate failed!", e); } catch (KeyStoreException e) { throw new CertificateStoreException("Loading certificate failed!", e); } catch (KeyManagementException e) { throw new CertificateStoreException("Loading certificate failed!", e); } }
From source file:com.appdynamics.monitors.azure.statsCollector.AzureServiceBusStatsCollector.java
private SSLSocketFactory getSSLSocketFactory(String keyStoreName, String password) { KeyStore ks = getKeyStore(keyStoreName, password); KeyManagerFactory keyManagerFactory = null; try {// www . j a v a2 s .c om keyManagerFactory = KeyManagerFactory.getInstance("SunX509"); keyManagerFactory.init(ks, password.toCharArray()); SSLContext context = SSLContext.getInstance("TLS"); context.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom()); return context.getSocketFactory(); } catch (NoSuchAlgorithmException e) { logger.error(e.getMessage(), e); throw new RuntimeException(e.getMessage(), e); } catch (KeyStoreException e) { logger.error(e.getMessage(), e); throw new RuntimeException(e.getMessage(), e); } catch (UnrecoverableKeyException e) { logger.error(e.getMessage(), e); throw new RuntimeException(e.getMessage(), e); } catch (KeyManagementException e) { logger.error(e.getMessage(), e); throw new RuntimeException(e.getMessage(), e); } }
From source file:org.openecomp.sdnc.sli.aai.AAIService.java
public AAIService(URL propURL) { LOG.info("Entered AAIService.ctor"); String runtime = System.getProperty("aaiclient.runtime"); if (runtime != null && runtime.equals("OSGI")) { runtimeOSGI = true;/* www . j ava 2 s . c om*/ } else { runtimeOSGI = false; } Properties props = null; try { props = initialize(propURL); AAIRequest.setProperties(props, this); } catch (Exception exc) { LOG.error("AicAAIResource.static", exc); } executor = new AAIRequestExecutor(); user_name = props.getProperty(CLIENT_NAME); user_password = props.getProperty(CLIENT_PWWD); if (user_name == null || user_name.isEmpty()) { LOG.debug("Basic user name is not set"); } if (user_password == null || user_password.isEmpty()) { LOG.debug("Basic password is not set"); } truststore_path = props.getProperty(TRUSTSTORE_PATH); truststore_password = props.getProperty(TRUSTSTORE_PSSWD); keystore_path = props.getProperty(KEYSTORE_PATH); keystore_password = props.getProperty(KEYSTORE_PSSWD); target_uri = props.getProperty(TARGET_URI); query_path = props.getProperty(QUERY_PATH); update_path = props.getProperty(UPDATE_PATH); String applicationId = props.getProperty(APPLICATION_ID); if (applicationId == null || applicationId.isEmpty()) { applicationId = "SDNC"; } application_id = applicationId; // connection timeout int tmpConnectionTimeout = 30000; int tmpReadTimeout = 30000; try { String tmpValue = null; tmpValue = props.getProperty(CONNECTION_TIMEOUT, "30000"); tmpConnectionTimeout = Integer.parseInt(tmpValue); tmpValue = props.getProperty(READ_TIMEOUT, "30000"); tmpReadTimeout = Integer.parseInt(tmpValue); } catch (Exception exc) { LOG.error("Failed setting connection timeout", exc); tmpConnectionTimeout = 30000; tmpReadTimeout = 30000; } connection_timeout = tmpConnectionTimeout; read_timeout = tmpReadTimeout; network_vserver_path = props.getProperty(NETWORK_VSERVER_PATH); svc_instance_path = props.getProperty(SVC_INSTANCE_PATH); // "/aai/v1/business/customers/customer/{customer-id}/service-subscriptions/service-subscription/{service-type}/service-instances"); // "/aai/v1/business/customers/customer/ma9181-203-customerid/service-subscriptions/service-subscription/ma9181%20Hosted%20Voice/service-instances"; // svc_inst_qry_path = props.getProperty(SVC_INST_QRY_PATH, "/aai/v1/search/generic-query?key=service-instance.service-instance-id:ma9181-204-instance&start-node-type=service-instance&include=service-instance"); svc_inst_qry_path = props.getProperty(SVC_INST_QRY_PATH); // "/aai/v1/search/generic-query?key=service-instance.service-instance-id:{svc-instance-id}&start-node-type=service-instance&include=service-instance"); param_service_type = props.getProperty(PARAM_SERVICE_TYPE, "service-type"); // P-Interfaces p_interface_path = props.getProperty(P_INTERFACE_PATH); vnf_image_query_path = props.getProperty(VNF_IMAGE_QUERY_PATH); ubb_notify_path = props.getProperty(UBB_NOTIFY_PATH); selflink_avpn = props.getProperty(SELFLINK_AVPN); selflink_fqdn = props.getProperty(SELFLINK_FQDN); service_path = props.getProperty(SERVICE_PATH); site_pair_set_path = props.getProperty(SITE_PAIR_SET_PATH); query_nodes_path = props.getProperty(QUERY_NODES_PATH); String iche = props.getProperty(CERTIFICATE_HOST_ERROR); boolean host_error = false; if (iche != null && !iche.isEmpty()) { host_error = Boolean.valueOf(iche); } ignore_certificate_host_error = host_error; HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { public boolean verify(String string, SSLSession ssls) { return ignore_certificate_host_error; } }); if (truststore_path != null && truststore_password != null && (new File(truststore_path)).exists()) { System.setProperty("javax.net.ssl.trustStore", truststore_path); System.setProperty("javax.net.ssl.trustStorePassword", truststore_password); } if (keystore_path != null && keystore_password != null && (new File(keystore_path)).exists()) { DefaultClientConfig config = new DefaultClientConfig(); //both jersey and HttpURLConnection can use this SSLContext ctx = null; try { ctx = SSLContext.getInstance("TLS"); KeyManagerFactory kmf = null; try { String def = "SunX509"; String storeType = "PKCS12"; def = KeyStore.getDefaultType(); kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); FileInputStream fin = new FileInputStream(keystore_path); // KeyStore ks = KeyStore.getInstance("PKCS12"); String extension = keystore_path.substring(keystore_path.lastIndexOf(".") + 1); if (extension != null && !extension.isEmpty() && extension.equalsIgnoreCase("JKS")) { storeType = "JKS"; } KeyStore ks = KeyStore.getInstance(storeType); char[] pwd = keystore_password.toCharArray(); ks.load(fin, pwd); kmf.init(ks, pwd); } catch (Exception ex) { LOG.error("AAIResource", ex); } ctx.init(kmf.getKeyManagers(), null, null); config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties(new HostnameVerifier() { @Override public boolean verify(String s, SSLSession sslSession) { return ignore_certificate_host_error; } }, ctx)); CTX = ctx; LOG.debug("SSLContext created"); } catch (KeyManagementException | NoSuchAlgorithmException exc) { LOG.error("AAIResource", exc); } } LOG.info("AAIResource.ctor initialized."); try { Field methodsField = HttpURLConnection.class.getDeclaredField("methods"); methodsField.setAccessible(true); // get the methods field modifiers Field modifiersField = Field.class.getDeclaredField("modifiers"); // bypass the "private" modifier modifiersField.setAccessible(true); // remove the "final" modifier modifiersField.setInt(methodsField, methodsField.getModifiers() & ~Modifier.FINAL); /* valid HTTP methods */ String[] methods = { "GET", "POST", "HEAD", "OPTIONS", "PUT", "DELETE", "TRACE", "PATCH" }; // set the new methods - including patch methodsField.set(null, methods); } catch (SecurityException | IllegalArgumentException | IllegalAccessException | NoSuchFieldException e) { e.printStackTrace(); } }
From source file:ddf.security.sts.claimsHandler.ClaimsHandlerManager.java
public static KeyManagerFactory createKeyManagerFactory(String keyStoreLoc, String keyStorePass) throws IOException { KeyManagerFactory kmf;/*from ww w . j ava2 s. com*/ try { // keystore stuff KeyStore keyStore = KeyStore.getInstance(System.getProperty("javax.net.ssl.keyStoreType")); LOGGER.debug("keyStoreLoc = {}", keyStoreLoc); FileInputStream keyFIS = new FileInputStream(keyStoreLoc); try { LOGGER.debug("Loading keyStore"); keyStore.load(keyFIS, keyStorePass.toCharArray()); } catch (CertificateException e) { throw new IOException("Unable to load certificates from keystore. " + keyStoreLoc, e); } finally { IOUtils.closeQuietly(keyFIS); } kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(keyStore, keyStorePass.toCharArray()); LOGGER.debug("key manager factory initialized"); } catch (NoSuchAlgorithmException e) { throw new IOException( "Problems creating SSL socket. Usually this is " + "referring to the certificate sent by the server not being trusted by the client.", e); } catch (UnrecoverableKeyException e) { throw new IOException("Unable to load keystore. " + keyStoreLoc, e); } catch (KeyStoreException e) { throw new IOException("Unable to read keystore. " + keyStoreLoc, e); } return kmf; }
From source file:net.roboconf.target.azure.internal.AzureIaasHandler.java
private SSLSocketFactory getSSLSocketFactory(String keyStoreName, String password) throws GeneralSecurityException, IOException { KeyStore ks = this.getKeyStore(keyStoreName, password); KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509"); keyManagerFactory.init(ks, password.toCharArray()); SSLContext context = SSLContext.getInstance("TLS"); context.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom()); return context.getSocketFactory(); }
From source file:net.java.sip.communicator.impl.certificate.CertificateServiceImpl.java
public SSLContext getSSLContext(X509TrustManager trustManager) throws GeneralSecurityException { try {//from w w w . j a va 2 s . c o m KeyStore ks = KeyStore .getInstance(System.getProperty("javax.net.ssl.keyStoreType", KeyStore.getDefaultType())); KeyManagerFactory kmFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); String keyStorePassword = System.getProperty("javax.net.ssl.keyStorePassword"); if (System.getProperty("javax.net.ssl.keyStore") != null) { ks.load(new FileInputStream(System.getProperty("javax.net.ssl.keyStore")), null); } else { ks.load(null, null); } kmFactory.init(ks, keyStorePassword == null ? null : keyStorePassword.toCharArray()); return getSSLContext(kmFactory.getKeyManagers(), trustManager); } catch (Exception e) { throw new GeneralSecurityException("Cannot init SSLContext", e); } }
From source file:org.apache.nifi.cluster.coordination.http.replication.okhttp.OkHttpReplicationClient.java
private Tuple<SSLSocketFactory, X509TrustManager> createSslSocketFactory(final NiFiProperties properties) { final SSLContext sslContext = SslContextFactory.createSslContext(properties); if (sslContext == null) { return null; }//from www .ja va 2 s . co m try { final KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("X509"); // initialize the KeyManager array to null and we will overwrite later if a keystore is loaded KeyManager[] keyManagers = null; // we will only initialize the keystore if properties have been supplied by the SSLContextService final String keystoreLocation = properties.getProperty(NiFiProperties.SECURITY_KEYSTORE); final String keystorePass = properties.getProperty(NiFiProperties.SECURITY_KEYSTORE_PASSWD); final String keystoreType = properties.getProperty(NiFiProperties.SECURITY_KEYSTORE_TYPE); // prepare the keystore final KeyStore keyStore = KeyStore.getInstance(keystoreType); try (FileInputStream keyStoreStream = new FileInputStream(keystoreLocation)) { keyStore.load(keyStoreStream, keystorePass.toCharArray()); } keyManagerFactory.init(keyStore, keystorePass.toCharArray()); keyManagers = keyManagerFactory.getKeyManagers(); // we will only initialize the truststure if properties have been supplied by the SSLContextService // load truststore final String truststoreLocation = properties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE); final String truststorePass = properties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_PASSWD); final String truststoreType = properties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_TYPE); KeyStore truststore = KeyStore.getInstance(truststoreType); truststore.load(new FileInputStream(truststoreLocation), truststorePass.toCharArray()); trustManagerFactory.init(truststore); // TrustManagerFactory.getTrustManagers returns a trust manager for each type of trust material. Since we are getting a trust manager factory that uses "X509" // as it's trust management algorithm, we are able to grab the first (and thus the most preferred) and use it as our x509 Trust Manager // // https://docs.oracle.com/javase/8/docs/api/javax/net/ssl/TrustManagerFactory.html#getTrustManagers-- final X509TrustManager x509TrustManager; TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); if (trustManagers[0] != null) { x509TrustManager = (X509TrustManager) trustManagers[0]; } else { throw new IllegalStateException("List of trust managers is null"); } // if keystore properties were not supplied, the keyManagers array will be null sslContext.init(keyManagers, trustManagerFactory.getTrustManagers(), null); final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); return new Tuple<>(sslSocketFactory, x509TrustManager); } catch (final Exception e) { throw new RuntimeException( "Failed to create SSL Socket Factory for replicating requests across the cluster"); } }