List of usage examples for javax.net.ssl KeyManagerFactory getDefaultAlgorithm
public static final String getDefaultAlgorithm()
From source file:org.apache.commons.vfs2.util.NHttpServer.java
public void runBlock(final int port, final File docRoot) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException, KeyManagementException { if (docRoot == null) { throw new IllegalArgumentException("No doc root specified."); }// ww w . ja v a2s.c o m // HTTP parameters for the server final HttpParams params = new SyncBasicHttpParams(); params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true) .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpTest/1.1"); // Create HTTP protocol processing chain final HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] { // Use standard server-side protocol interceptors new ResponseDate(), new ResponseServer(), new ResponseContent(), new ResponseConnControl() }); // Create request handler registry final HttpAsyncRequestHandlerRegistry reqistry = new HttpAsyncRequestHandlerRegistry(); // Register the default handler for all URIs reqistry.register("*", new HttpFileHandler(docRoot)); // Create server-side HTTP protocol handler final HttpAsyncService protocolHandler = new HttpAsyncService(httpproc, new DefaultConnectionReuseStrategy(), reqistry, params) { @Override public void closed(final NHttpServerConnection conn) { NHttpServer.debug(conn + ": connection closed"); super.closed(conn); } @Override public void connected(final NHttpServerConnection conn) { NHttpServer.debug(conn + ": connection open"); super.connected(conn); } }; // Create HTTP connection factory NHttpConnectionFactory<DefaultNHttpServerConnection> connFactory; if (port == 8443) { // Initialize SSL context final ClassLoader cl = NHttpServer.class.getClassLoader(); final URL url = cl.getResource("my.keystore"); if (url == null) { NHttpServer.debug("Keystore not found"); System.exit(1); } final KeyStore keystore = KeyStore.getInstance("jks"); keystore.load(url.openStream(), "secret".toCharArray()); final KeyManagerFactory kmfactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmfactory.init(keystore, "secret".toCharArray()); final KeyManager[] keymanagers = kmfactory.getKeyManagers(); final SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(keymanagers, null, null); connFactory = new SSLNHttpServerConnectionFactory(sslcontext, null, params); } else { connFactory = new DefaultNHttpServerConnectionFactory(params); } // Create server-side I/O event dispatch final IOEventDispatch ioEventDispatch = new DefaultHttpServerIODispatch(protocolHandler, connFactory); // Create server-side I/O reactor this.ioReactor = new DefaultListeningIOReactor(); try { // Listen of the given port this.ioReactor.listen(new InetSocketAddress(port)); // Ready to go! this.ioReactor.execute(ioEventDispatch); } catch (final InterruptedIOException ex) { System.err.println("Interrupted"); } catch (final IOException e) { System.err.println("I/O error: " + e.getMessage()); } NHttpServer.debug("Shutdown"); }
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 .j a va2 s .c om */ 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 ww . j a va 2 s . 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.apache.nifi.processors.grpc.InvokeGRPC.java
/** * Whenever this processor is triggered, we need to construct a client in order to communicate * with the configured gRPC service./*from w w w . j av a2 s. c o m*/ * * @param context the processor context */ @OnScheduled public void initializeClient(final ProcessContext context) throws Exception { channelReference.set(null); blockingStubReference.set(null); final ComponentLog logger = getLogger(); final String host = context.getProperty(PROP_SERVICE_HOST).getValue(); final int port = context.getProperty(PROP_SERVICE_PORT).asInteger(); final Integer maxMessageSize = context.getProperty(PROP_MAX_MESSAGE_SIZE).asDataSize(DataUnit.B).intValue(); String userAgent = USER_AGENT_PREFIX; try { userAgent += "_" + InetAddress.getLocalHost().getHostName(); } catch (final UnknownHostException e) { logger.warn("Unable to determine local hostname. Defaulting gRPC user agent to {}.", new Object[] { USER_AGENT_PREFIX }, e); } final NettyChannelBuilder nettyChannelBuilder = NettyChannelBuilder.forAddress(host, port) // supports both gzip and plaintext, but will compress by default. .compressorRegistry(CompressorRegistry.getDefaultInstance()) .decompressorRegistry(DecompressorRegistry.getDefaultInstance()) .maxInboundMessageSize(maxMessageSize).userAgent(userAgent); // configure whether or not we're using secure comms final boolean useSecure = context.getProperty(PROP_USE_SECURE).asBoolean(); final SSLContextService sslContextService = context.getProperty(PROP_SSL_CONTEXT_SERVICE) .asControllerService(SSLContextService.class); final SSLContext sslContext = sslContextService == null ? null : sslContextService.createSSLContext(SSLContextService.ClientAuth.NONE); if (useSecure && sslContext != null) { SslContextBuilder sslContextBuilder = GrpcSslContexts.forClient(); if (StringUtils.isNotBlank(sslContextService.getKeyStoreFile())) { final KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm(), sslContext.getProvider()); final KeyStore keyStore = KeyStore.getInstance(sslContextService.getKeyStoreType()); try (final InputStream is = new FileInputStream(sslContextService.getKeyStoreFile())) { keyStore.load(is, sslContextService.getKeyStorePassword().toCharArray()); } keyManagerFactory.init(keyStore, sslContextService.getKeyStorePassword().toCharArray()); sslContextBuilder.keyManager(keyManagerFactory); } if (StringUtils.isNotBlank(sslContextService.getTrustStoreFile())) { final TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm(), sslContext.getProvider()); final KeyStore trustStore = KeyStore.getInstance(sslContextService.getTrustStoreType()); try (final InputStream is = new FileInputStream(sslContextService.getTrustStoreFile())) { trustStore.load(is, sslContextService.getTrustStorePassword().toCharArray()); } trustManagerFactory.init(trustStore); sslContextBuilder.trustManager(trustManagerFactory); } nettyChannelBuilder.sslContext(sslContextBuilder.build()); } else { nettyChannelBuilder.usePlaintext(true); } final ManagedChannel channel = nettyChannelBuilder.build(); final FlowFileServiceGrpc.FlowFileServiceBlockingStub blockingStub = FlowFileServiceGrpc .newBlockingStub(channel); channelReference.set(channel); blockingStubReference.set(blockingStub); }
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;/* w w w .j a v a 2s . c o m*/ } 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;// w w w. ja v a 2s .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.java.sip.communicator.impl.certificate.CertificateServiceImpl.java
public SSLContext getSSLContext(X509TrustManager trustManager) throws GeneralSecurityException { try {/*from w w w . ja v a2s . 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 w w w .j a va2 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"); } }
From source file:ddf.metrics.plugin.webconsole.MetricsWebConsolePlugin.java
private void configureHttps(WebClient client) { LOGGER.debug("Configuring client for HTTPS"); HTTPConduit conduit = WebClient.getConfig(client).getHttpConduit(); if (null != conduit) { TLSClientParameters params = conduit.getTlsClientParameters(); if (params == null) { params = new TLSClientParameters(); }/*from w w w .j a v a 2 s.c o m*/ params.setDisableCNCheck(true); KeyStore keyStore; KeyStore trustStore; FileInputStream tsFIS = null; FileInputStream ksFIS = null; try { String trustStorePath = System.getProperty("javax.net.ssl.trustStore"); String trustStoreType = System.getProperty("javax.net.ssl.trustStoreType"); String trustStorePassword = System.getProperty("javax.net.ssl.trustStorePassword"); trustStore = KeyStore.getInstance(trustStoreType); File trustStoreFile = new File(trustStorePath); tsFIS = new FileInputStream(trustStoreFile); trustStore.load(tsFIS, trustStorePassword.toCharArray()); String keyStorePath = System.getProperty("javax.net.ssl.keyStore"); String keyStoreType = System.getProperty("javax.net.ssl.keyStoreType"); String keyStorePassword = System.getProperty("javax.net.ssl.keyStorePassword"); keyStore = KeyStore.getInstance(keyStoreType); File keyStoreFile = new File(keyStorePath); ksFIS = new FileInputStream(keyStoreFile); keyStore.load(ksFIS, keyStorePassword.toCharArray()); TrustManagerFactory trustFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustFactory.init(trustStore); TrustManager[] tm = trustFactory.getTrustManagers(); params.setTrustManagers(tm); KeyManagerFactory keyFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyFactory.init(keyStore, keyStorePassword.toCharArray()); KeyManager[] km = keyFactory.getKeyManagers(); params.setKeyManagers(km); conduit.setTlsClientParameters(params); } catch (KeyStoreException e) { handleKeyStoreException(e); } catch (NoSuchAlgorithmException e) { handleKeyStoreException(e); } catch (CertificateException e) { handleKeyStoreException(e); } catch (FileNotFoundException e) { handleKeyStoreException(e); } catch (IOException e) { handleKeyStoreException(e); } catch (UnrecoverableKeyException e) { handleKeyStoreException(e); } finally { if (null != tsFIS) { IOUtils.closeQuietly(tsFIS); } if (null != ksFIS) { IOUtils.closeQuietly(ksFIS); } } } else { LOGGER.warn("HTTP Conduit returned by the web client was NULL."); } }