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:it.paolorendano.clm.AbstractCassandraDAO.java
/** * Gets the SSL context.//w w w. j ava 2 s .c o m * * @param truststorePath the truststore path * @param truststorePassword the truststore password * @param keystorePath the keystore path * @param keystorePassword the keystore password * @return the SSL context * @throws NoSuchAlgorithmException the no such algorithm exception * @throws KeyStoreException the key store exception * @throws CertificateException the certificate exception * @throws IOException Signals that an I/O exception has occurred. * @throws UnrecoverableKeyException the unrecoverable key exception * @throws KeyManagementException the key management exception */ private static SSLContext getSSLContext(String truststorePath, String truststorePassword, String keystorePath, String keystorePassword) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException, UnrecoverableKeyException, KeyManagementException { /* taken from http://www.datastax.com/dev/blog/accessing-secure-dse-clusters-with-cql-native-protocol */ FileInputStream tsf = new FileInputStream(truststorePath); FileInputStream ksf = new FileInputStream(keystorePath); SSLContext ctx = SSLContext.getInstance("SSL"); KeyStore ts = KeyStore.getInstance("JKS"); ts.load(tsf, truststorePassword.toCharArray()); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ts); KeyStore ks = KeyStore.getInstance("JKS"); ks.load(ksf, keystorePassword.toCharArray()); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(ks, keystorePassword.toCharArray()); ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom()); return ctx; }
From source file:org.mule.api.security.tls.TlsConfiguration.java
private void initKeyManagerFactory() throws CreateException { if (logger.isDebugEnabled()) { logger.debug("initialising key manager factory from keystore data"); }/* w w w .j a va2s. c om*/ KeyStore tempKeyStore; try { tempKeyStore = loadKeyStore(); checkKeyStoreContainsAlias(tempKeyStore); } catch (Exception e) { throw new CreateException(CoreMessages.failedToLoad("KeyStore: " + keyStoreName), e, this); } try { keyManagerFactory = KeyManagerFactory.getInstance(getKeyManagerAlgorithm()); keyManagerFactory.init(tempKeyStore, keyPassword.toCharArray()); } catch (Exception e) { throw new CreateException(CoreMessages.failedToLoad("Key Manager"), e, this); } }
From source file:org.apache.axis2.transport.rabbitmq.RabbitMQConnectionFactory.java
/** * Initialize connection factory/*from w w w .j a v a 2 s . c o m*/ */ private void initConnectionFactory() { connectionFactory = new ConnectionFactory(); String hostName = parameters.get(RabbitMQConstants.SERVER_HOST_NAME); String portValue = parameters.get(RabbitMQConstants.SERVER_PORT); String serverRetryIntervalS = parameters.get(RabbitMQConstants.SERVER_RETRY_INTERVAL); String retryIntervalS = parameters.get(RabbitMQConstants.RETRY_INTERVAL); String retryCountS = parameters.get(RabbitMQConstants.RETRY_COUNT); String heartbeat = parameters.get(RabbitMQConstants.HEARTBEAT); String connectionTimeout = parameters.get(RabbitMQConstants.CONNECTION_TIMEOUT); String sslEnabledS = parameters.get(RabbitMQConstants.SSL_ENABLED); String userName = parameters.get(RabbitMQConstants.SERVER_USER_NAME); String password = parameters.get(RabbitMQConstants.SERVER_PASSWORD); String virtualHost = parameters.get(RabbitMQConstants.SERVER_VIRTUAL_HOST); if (!StringUtils.isEmpty(heartbeat)) { try { int heartbeatValue = Integer.parseInt(heartbeat); connectionFactory.setRequestedHeartbeat(heartbeatValue); } catch (NumberFormatException e) { //proceeding with rabbitmq default value log.warn("Number format error in reading heartbeat value. Proceeding with default"); } } if (!StringUtils.isEmpty(connectionTimeout)) { try { int connectionTimeoutValue = Integer.parseInt(connectionTimeout); connectionFactory.setConnectionTimeout(connectionTimeoutValue); } catch (NumberFormatException e) { //proceeding with rabbitmq default value log.warn("Number format error in reading connection timeout value. Proceeding with default"); } } if (!StringUtils.isEmpty(sslEnabledS)) { try { boolean sslEnabled = Boolean.parseBoolean(sslEnabledS); if (sslEnabled) { String keyStoreLocation = parameters.get(RabbitMQConstants.SSL_KEYSTORE_LOCATION); String keyStoreType = parameters.get(RabbitMQConstants.SSL_KEYSTORE_TYPE); String keyStorePassword = parameters.get(RabbitMQConstants.SSL_KEYSTORE_PASSWORD); String trustStoreLocation = parameters.get(RabbitMQConstants.SSL_TRUSTSTORE_LOCATION); String trustStoreType = parameters.get(RabbitMQConstants.SSL_TRUSTSTORE_TYPE); String trustStorePassword = parameters.get(RabbitMQConstants.SSL_TRUSTSTORE_PASSWORD); String sslVersion = parameters.get(RabbitMQConstants.SSL_VERSION); if (StringUtils.isEmpty(keyStoreLocation) || StringUtils.isEmpty(keyStoreType) || StringUtils.isEmpty(keyStorePassword) || StringUtils.isEmpty(trustStoreLocation) || StringUtils.isEmpty(trustStoreType) || StringUtils.isEmpty(trustStorePassword)) { log.warn( "Trustore and keystore information is not provided correctly. Proceeding with default SSL configuration"); connectionFactory.useSslProtocol(); } else { char[] keyPassphrase = keyStorePassword.toCharArray(); KeyStore ks = KeyStore.getInstance(keyStoreType); ks.load(new FileInputStream(keyStoreLocation), keyPassphrase); KeyManagerFactory kmf = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(ks, keyPassphrase); char[] trustPassphrase = trustStorePassword.toCharArray(); KeyStore tks = KeyStore.getInstance(trustStoreType); tks.load(new FileInputStream(trustStoreLocation), trustPassphrase); TrustManagerFactory tmf = TrustManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); tmf.init(tks); SSLContext c = SSLContext.getInstance(sslVersion); c.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); connectionFactory.useSslProtocol(c); } } } catch (Exception e) { log.warn("Format error in SSL enabled value. Proceeding without enabling SSL", e); } } if (!StringUtils.isEmpty(retryCountS)) { try { retryCount = Integer.parseInt(retryCountS); } catch (NumberFormatException e) { log.warn("Number format error in reading retry count value. Proceeding with default value (3)", e); } } if (!StringUtils.isEmpty(hostName)) { connectionFactory.setHost(hostName); } else { handleException("Host name is not defined"); } try { int port = Integer.parseInt(portValue); if (port > 0) { connectionFactory.setPort(port); } } catch (NumberFormatException e) { handleException("Number format error in port number", e); } if (!StringUtils.isEmpty(userName)) { connectionFactory.setUsername(userName); } if (!StringUtils.isEmpty(password)) { connectionFactory.setPassword(password); } if (!StringUtils.isEmpty(virtualHost)) { connectionFactory.setVirtualHost(virtualHost); } if (!StringUtils.isEmpty(retryIntervalS)) { try { retryInterval = Integer.parseInt(retryIntervalS); } catch (NumberFormatException e) { log.warn( "Number format error in reading retry interval value. Proceeding with default value (30000ms)", e); } } if (!StringUtils.isEmpty(serverRetryIntervalS)) { try { int serverRetryInterval = Integer.parseInt(serverRetryIntervalS); connectionFactory.setNetworkRecoveryInterval(serverRetryInterval); } catch (NumberFormatException e) { log.warn( "Number format error in reading server retry interval value. Proceeding with default value", e); } } connectionFactory.setAutomaticRecoveryEnabled(true); connectionFactory.setTopologyRecoveryEnabled(false); }
From source file:orca.ektorp.client.ContextualSSLSocketFactory.java
private static SSLContext createSSLContext(String algorithm, final KeyStore keystore, final String keystorePassword, final KeyStore truststore, final SecureRandom random, final TrustStrategy trustStrategy) throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, KeyManagementException { if (algorithm == null) { algorithm = TLS;// w w w . java 2 s.co m } KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmfactory.init(keystore, keystorePassword != null ? keystorePassword.toCharArray() : null); KeyManager[] keymanagers = kmfactory.getKeyManagers(); TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmfactory.init(truststore); TrustManager[] trustmanagers = tmfactory.getTrustManagers(); if (trustmanagers != null && trustStrategy != null) { for (int i = 0; i < trustmanagers.length; i++) { TrustManager tm = trustmanagers[i]; /* * @TODO: I need to uncomment the 3 lines below. TrustManagerDecorator is not public (package visibility) */ // if (tm instanceof X509TrustManager) { // trustmanagers[i] = new TrustManagerDecorator( // (X509TrustManager) tm, trustStrategy); //} } } SSLContext sslcontext = SSLContext.getInstance(algorithm); sslcontext.init(keymanagers, trustmanagers, random); return sslcontext; }
From source file:io.atomix.cluster.messaging.impl.NettyMessagingService.java
private boolean loadKeyStores() { // Maintain a local copy of the trust and key managers in case anything goes wrong TrustManagerFactory tmf;//from www . java 2 s . com KeyManagerFactory kmf; try { String ksLocation = System.getProperty("javax.net.ssl.keyStore", DEFAULT_KS_FILE.toString()); String tsLocation = System.getProperty("javax.net.ssl.trustStore", DEFAULT_KS_FILE.toString()); char[] ksPwd = System.getProperty("javax.net.ssl.keyStorePassword", DEFAULT_KS_PASSWORD).toCharArray(); char[] tsPwd = System.getProperty("javax.net.ssl.trustStorePassword", DEFAULT_KS_PASSWORD) .toCharArray(); tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); KeyStore ts = KeyStore.getInstance(KeyStore.getDefaultType()); try (FileInputStream fileInputStream = new FileInputStream(tsLocation)) { ts.load(fileInputStream, tsPwd); } tmf.init(ts); kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); try (FileInputStream fileInputStream = new FileInputStream(ksLocation)) { ks.load(fileInputStream, ksPwd); } kmf.init(ks, ksPwd); if (log.isInfoEnabled()) { logKeyStore(ks, ksLocation, ksPwd); } } catch (FileNotFoundException e) { log.warn("Disabling TLS for intra-cluster messaging; Could not load cluster key store: {}", e.getMessage()); return TLS_DISABLED; } catch (Exception e) { //TODO we might want to catch exceptions more specifically log.error("Error loading key store; disabling TLS for intra-cluster messaging", e); return TLS_DISABLED; } this.trustManager = tmf; this.keyManager = kmf; return TLS_ENABLED; }
From source file:org.wso2.carbon.identity.application.authentication.endpoint.util.MutualSSLManager.java
/** * Create basic SSL connection factory/*w ww. j a va2 s .c o m*/ * * @throws AuthenticationException */ public static void initMutualSSLConnection(boolean hostNameVerificationEnabled) throws AuthenticationException { try { KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(keyManagerType); keyManagerFactory.init(keyStore, keyStorePassword); TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(trustManagerType); trustManagerFactory.init(trustStore); // Create and initialize SSLContext for HTTPS communication SSLContext sslContext = SSLContext.getInstance(protocol); if (hostNameVerificationEnabled) { sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null); sslSocketFactory = sslContext.getSocketFactory(); if (log.isDebugEnabled()) { log.debug("Mutual SSL Client initialized with Hostname Verification enabled"); } } else { // All the code below is to overcome host name verification failure we get in certificate // validation due to self signed certificate. // Create empty HostnameVerifier HostnameVerifier hv = new HostnameVerifier() { @Override public boolean verify(String urlHostName, SSLSession session) { return true; } }; // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return new java.security.cert.X509Certificate[0]; } @Override public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { /* skipped implementation */ } @Override public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) { /* skipped implementation */ } } }; sslContext.init(keyManagerFactory.getKeyManagers(), trustAllCerts, new java.security.SecureRandom()); if (log.isDebugEnabled()) { log.debug("SSL Context is initialized with trust manager for excluding certificate validation"); } SSLContext.setDefault(sslContext); sslSocketFactory = sslContext.getSocketFactory(); HttpsURLConnection.setDefaultHostnameVerifier(hv); if (log.isDebugEnabled()) { log.debug("Mutual SSL Client initialized with Hostname Verification disabled"); } } } catch (UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) { throw new AuthenticationException("Error while trying to load Trust Store.", e); } }
From source file:com.bytelightning.opensource.pokerface.PokerFace.java
/** * Configures all the needed components, but does not actually start the server. * @param config Contains all information needed to fully wire up the http, https, and httpclient components of this reverse proxy. * @throws Exception Yeah, a lot can go wrong here, but at least it will be caught immediately :-) *//*from w ww. ja va2 s. c o m*/ public void config(HierarchicalConfiguration config) throws Exception { List<HierarchicalConfiguration> lconf; HttpAsyncRequester executor = null; BasicNIOConnPool connPool = null; ObjectPool<ByteBuffer> byteBufferPool = null; LinkedHashMap<String, TargetDescriptor> mappings = null; ConcurrentMap<String, HttpHost> hosts = null; handlerRegistry = new UriHttpAsyncRequestHandlerMapper(); // Initialize the keystore (if one was specified) KeyStore keystore = null; char[] keypass = null; String keystoreUri = config.getString("keystore"); if ((keystoreUri != null) && (keystoreUri.trim().length() > 0)) { Path keystorePath = Utils.MakePath(keystoreUri); if (!Files.exists(keystorePath)) throw new ConfigurationException("Keystore does not exist."); if (Files.isDirectory(keystorePath)) throw new ConfigurationException("Keystore is not a file"); String storepass = config.getString("storepass"); if ((storepass != null) && "null".equals(storepass)) storepass = null; keystore = KeyStore.getInstance(KeyStore.getDefaultType()); try (InputStream keyStoreStream = Files.newInputStream(keystorePath)) { keystore.load(keyStoreStream, storepass == null ? null : storepass.trim().toCharArray()); } catch (IOException ex) { Logger.error("Unable to load https server keystore from " + keystoreUri); return; } keypass = config.getString("keypass").trim().toCharArray(); } // Wire up the listening reactor lconf = config.configurationsAt("server"); if ((lconf == null) || (lconf.size() != 1)) throw new ConfigurationException("One (and only one) server configuration element is allowed."); else { Builder builder = IOReactorConfig.custom(); builder.setIoThreadCount(ComputeReactorProcessors(config.getDouble("server[@cpu]", 0.667))); builder.setSoTimeout(config.getInt("server[@soTimeout]", 0)); builder.setSoLinger(config.getInt("server[@soLinger]", -1)); builder.setSoReuseAddress(true); builder.setTcpNoDelay(false); builder.setSelectInterval(100); IOReactorConfig rconfig = builder.build(); Logger.info("Configuring server with options: " + rconfig.toString()); listeningReactor = new DefaultListeningIOReactor(rconfig); lconf = config.configurationsAt("server.listen"); InetSocketAddress addr; boolean hasNonWildcardSecure = false; LinkedHashMap<SocketAddress, SSLContext> addrSSLContext = new LinkedHashMap<SocketAddress, SSLContext>(); if ((lconf == null) || (lconf.size() == 0)) { addr = new InetSocketAddress("127.0.0.1", 8080); ListenerEndpoint ep = listeningReactor.listen(addr); Logger.warn("Configured " + ep.getAddress()); } else { TrustManager[] trustManagers = null; KeyManagerFactory kmf = null; // Create all the specified listeners. for (HierarchicalConfiguration hc : lconf) { String addrStr = hc.getString("[@address]"); if ((addrStr == null) || (addrStr.length() == 0)) addrStr = "0.0.0.0"; String alias = hc.getString("[@alias]"); int port = hc.getInt("[@port]", alias != null ? 443 : 80); addr = new InetSocketAddress(addrStr, port); ListenerEndpoint ep = listeningReactor.listen(addr); String protocol = hc.containsKey("[@protocol]") ? hc.getString("[@protocol]") : null; Boolean secure = hc.containsKey("[@secure]") ? hc.getBoolean("[@secure]") : null; if ((alias != null) && (secure == null)) secure = true; if ((protocol != null) && (secure == null)) secure = true; if ((secure != null) && secure) { if (protocol == null) protocol = "TLS"; if (keystore == null) throw new ConfigurationException( "An https listening socket was requested, but no keystore was specified."); if (kmf == null) { kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(keystore, keypass); } // Are we going to trust all clients or just specific ones? if (hc.getBoolean("[@trustAny]", true)) trustManagers = new TrustManager[] { new X509TrustAllManager() }; else { TrustManagerFactory instance = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); instance.init(keystore); trustManagers = instance.getTrustManagers(); } KeyManager[] keyManagers = kmf.getKeyManagers(); if (alias != null) for (int i = 0; i < keyManagers.length; i++) { if (keyManagers[i] instanceof X509ExtendedKeyManager) keyManagers[i] = new PokerFaceKeyManager(alias, (X509ExtendedKeyManager) keyManagers[i]); } SSLContext sslCtx = SSLContext.getInstance(protocol); sslCtx.init(keyManagers, trustManagers, new SecureRandom()); if (addr.getAddress().isAnyLocalAddress()) { // This little optimization helps us respond faster for every connection as we don't have to extrapolate a local connection address to wild card. for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en .hasMoreElements();) { NetworkInterface intf = en.nextElement(); for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr .hasMoreElements();) { addr = new InetSocketAddress(enumIpAddr.nextElement(), port); addrSSLContext.put(addr, sslCtx); } } } else { addrSSLContext.put(addr, sslCtx); hasNonWildcardSecure = true; } } Logger.warn("Configured " + (alias == null ? "" : (protocol + " on")) + ep.getAddress()); } } // We will need an HTTP protocol processor for the incoming connections String serverAgent = config.getString("server.serverAgent", "PokerFace/" + Utils.Version); HttpProcessor inhttpproc = new ImmutableHttpProcessor( new HttpResponseInterceptor[] { new ResponseDateInterceptor(), new ResponseServer(serverAgent), new ResponseContent(), new ResponseConnControl() }); HttpAsyncService serviceHandler = new HttpAsyncService(inhttpproc, new DefaultConnectionReuseStrategy(), null, handlerRegistry, null) { public void exception(final NHttpServerConnection conn, final Exception cause) { Logger.warn(cause.getMessage()); super.exception(conn, cause); } }; if (addrSSLContext.size() > 0) { final SSLContext defaultCtx = addrSSLContext.values().iterator().next(); final Map<SocketAddress, SSLContext> sslMap; if ((!hasNonWildcardSecure) || (addrSSLContext.size() == 1)) sslMap = null; else sslMap = addrSSLContext; listeningDispatcher = new DefaultHttpServerIODispatch(serviceHandler, new SSLNHttpServerConnectionFactory(defaultCtx, null, ConnectionConfig.DEFAULT) { protected SSLIOSession createSSLIOSession(IOSession iosession, SSLContext sslcontext, SSLSetupHandler sslHandler) { SSLIOSession retVal; SSLContext sktCtx = sslcontext; if (sslMap != null) { SocketAddress la = iosession.getLocalAddress(); if (la != null) { sktCtx = sslMap.get(la); if (sktCtx == null) sktCtx = sslcontext; } retVal = new SSLIOSession(iosession, SSLMode.SERVER, sktCtx, sslHandler); } else retVal = super.createSSLIOSession(iosession, sktCtx, sslHandler); if (sktCtx != null) retVal.setAttribute("com.bytelightning.opensource.pokerface.secure", true); return retVal; } }); } else listeningDispatcher = new DefaultHttpServerIODispatch(serviceHandler, ConnectionConfig.DEFAULT); } // Configure the httpclient reactor that will be used to do reverse proxing to the specified targets. lconf = config.configurationsAt("targets"); if ((lconf != null) && (lconf.size() > 0)) { HierarchicalConfiguration conf = lconf.get(0); Builder builder = IOReactorConfig.custom(); builder.setIoThreadCount(ComputeReactorProcessors(config.getDouble("targets[@cpu]", 0.667))); builder.setSoTimeout(conf.getInt("targets[@soTimeout]", 0)); builder.setSoLinger(config.getInt("targets[@soLinger]", -1)); builder.setConnectTimeout(conf.getInt("targets[@connectTimeout]", 0)); builder.setSoReuseAddress(true); builder.setTcpNoDelay(false); connectingReactor = new DefaultConnectingIOReactor(builder.build()); final int bufferSize = conf.getInt("targets[@bufferSize]", 1024) * 1024; byteBufferPool = new SoftReferenceObjectPool<ByteBuffer>(new BasePooledObjectFactory<ByteBuffer>() { @Override public ByteBuffer create() throws Exception { return ByteBuffer.allocateDirect(bufferSize); } @Override public PooledObject<ByteBuffer> wrap(ByteBuffer buffer) { return new DefaultPooledObject<ByteBuffer>(buffer); } }); KeyManager[] keyManagers = null; TrustManager[] trustManagers = null; if (keystore != null) { KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(keystore, keypass); keyManagers = kmf.getKeyManagers(); } // Will the httpclient's trust any remote target, or only specific ones. if (conf.getBoolean("targets[@trustAny]", false)) trustManagers = new TrustManager[] { new X509TrustAllManager() }; else if (keystore != null) { TrustManagerFactory instance = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); instance.init(keystore); trustManagers = instance.getTrustManagers(); } SSLContext clientSSLContext = SSLContext.getInstance(conf.getString("targets[@protocol]", "TLS")); clientSSLContext.init(keyManagers, trustManagers, new SecureRandom()); // Setup an SSL capable connection pool for the httpclients. connPool = new BasicNIOConnPool(connectingReactor, new BasicNIOConnFactory(clientSSLContext, null, ConnectionConfig.DEFAULT), conf.getInt("targets[@connectTimeout]", 0)); connPool.setMaxTotal(conf.getInt("targets[@connMaxTotal]", 1023)); connPool.setDefaultMaxPerRoute(conf.getInt("targets[@connMaxPerRoute]", 1023)); // Set up HTTP protocol processor for outgoing connections String userAgent = conf.getString("targets.userAgent", "PokerFace/" + Utils.Version); HttpProcessor outhttpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { new RequestContent(), new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent(userAgent), new RequestExpectContinue(true) }); executor = new HttpAsyncRequester(outhttpproc, new DefaultConnectionReuseStrategy()); // Now set up all the configured targets. mappings = new LinkedHashMap<String, TargetDescriptor>(); hosts = new ConcurrentHashMap<String, HttpHost>(); String[] scheme = { null }; String[] host = { null }; int[] port = { 0 }; String[] path = { null }; int[] stripPrefixCount = { 0 }; for (HierarchicalConfiguration targetConfig : conf.configurationsAt("target")) { String match = targetConfig.getString("[@pattern]"); if ((match == null) || (match.trim().length() < 1)) { Logger.error("Unable to configure target; Invalid url match pattern"); continue; } String key = RequestForTargetConsumer.UriToTargetKey(targetConfig.getString("[@url]"), scheme, host, port, path, stripPrefixCount); if (key == null) { Logger.error("Unable to configure target"); continue; } HttpHost targetHost = hosts.get(key); if (targetHost == null) { targetHost = new HttpHost(host[0], port[0], scheme[0]); hosts.put(key, targetHost); } TargetDescriptor desc = new TargetDescriptor(targetHost, path[0], stripPrefixCount[0]); mappings.put(match, desc); } connectionDispatcher = new DefaultHttpClientIODispatch(new HttpAsyncRequestExecutor(), ConnectionConfig.DEFAULT); } // Allocate the script map which will be populated by it's own executor thread. if (config.containsKey("scripts.rootDirectory")) { Path tmp = Utils.MakePath(config.getProperty("scripts.rootDirectory")); if (!Files.exists(tmp)) throw new FileNotFoundException("Scripts directory does not exist."); if (!Files.isDirectory(tmp)) throw new FileNotFoundException("'scripts' path is not a directory."); scripts = new ConcurrentSkipListMap<String, ScriptObjectMirror>(); boolean watch = config.getBoolean("scripts.dynamicWatch", false); List<Path> jsLibs; Object prop = config.getProperty("scripts.library"); if (prop != null) { jsLibs = new ArrayList<Path>(); if (prop instanceof Collection<?>) { @SuppressWarnings("unchecked") Collection<Object> oprop = (Collection<Object>) prop; for (Object obj : oprop) jsLibs.add(Utils.MakePath(obj)); } else { jsLibs.add(Utils.MakePath(prop)); } } else jsLibs = null; lconf = config.configurationsAt("scripts.scriptConfig"); if (lconf != null) { if (lconf.size() > 1) throw new ConfigurationException("Only one scriptConfig element is allowed."); if (lconf.size() == 0) lconf = null; } HierarchicalConfiguration scriptConfig; if (lconf == null) scriptConfig = new HierarchicalConfiguration(); else scriptConfig = lconf.get(0); scriptConfig.setProperty("pokerface.scripts.rootDirectory", tmp.toString()); configureScripts(jsLibs, scriptConfig, tmp, watch); if (watch) ScriptDirectoryWatcher = new DirectoryWatchService(); } // Configure the static file directory (if any) Path staticFilesPath = null; if (config.containsKey("files.rootDirectory")) { Path tmp = Utils.MakePath(config.getProperty("files.rootDirectory")); if (!Files.exists(tmp)) throw new FileNotFoundException("Files directory does not exist."); if (!Files.isDirectory(tmp)) throw new FileNotFoundException("'files' path is not a directory."); staticFilesPath = tmp; List<HierarchicalConfiguration> mimeEntries = config.configurationsAt("files.mime-entry"); if (mimeEntries != null) { for (HierarchicalConfiguration entry : mimeEntries) { entry.setDelimiterParsingDisabled(true); String type = entry.getString("[@type]", "").trim(); if (type.length() == 0) throw new ConfigurationException("Invalid mime type entry"); String extensions = entry.getString("[@extensions]", "").trim(); if (extensions.length() == 0) throw new ConfigurationException("Invalid mime extensions for: " + type); ScriptHelperImpl.AddMimeEntry(type, extensions); } } } handlerRegistry.register("/*", new RequestHandler(executor, connPool, byteBufferPool, staticFilesPath, mappings, scripts != null ? Collections.unmodifiableNavigableMap(scripts) : null, config.getBoolean("scripts.allowScriptsToSpecifyDynamicHosts", false) ? hosts : null)); }
From source file:org.apache.synapse.transport.nhttp.config.ClientConnFactoryBuilder.java
private SSLContext createSSLContext(OMElement keyStoreElt, OMElement trustStoreElt, boolean novalidatecert) throws AxisFault { KeyManager[] keymanagers = null; TrustManager[] trustManagers = null; if (keyStoreElt != null) { String location = keyStoreElt.getFirstChildWithName(new QName("Location")).getText(); String type = keyStoreElt.getFirstChildWithName(new QName("Type")).getText(); String storePassword = keyStoreElt.getFirstChildWithName(new QName("Password")).getText(); String keyPassword = keyStoreElt.getFirstChildWithName(new QName("KeyPassword")).getText(); FileInputStream fis = null; try {//from w w w . j a v a 2 s. c o m KeyStore keyStore = KeyStore.getInstance(type); fis = new FileInputStream(location); if (log.isInfoEnabled()) { log.info(name + " Loading Identity Keystore from : " + location); } keyStore.load(fis, storePassword.toCharArray()); KeyManagerFactory kmfactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmfactory.init(keyStore, keyPassword.toCharArray()); keymanagers = kmfactory.getKeyManagers(); } catch (GeneralSecurityException gse) { log.error(name + " Error loading Keystore : " + location, gse); throw new AxisFault("Error loading Keystore : " + location, gse); } catch (IOException ioe) { log.error(name + " Error opening Keystore : " + location, ioe); throw new AxisFault("Error opening Keystore : " + location, ioe); } finally { if (fis != null) { try { fis.close(); } catch (IOException ignore) { } } } } if (trustStoreElt != null) { if (novalidatecert && log.isWarnEnabled()) { log.warn(name + " Ignoring novalidatecert parameter since a truststore has been specified"); } String location = trustStoreElt.getFirstChildWithName(new QName("Location")).getText(); String type = trustStoreElt.getFirstChildWithName(new QName("Type")).getText(); String storePassword = trustStoreElt.getFirstChildWithName(new QName("Password")).getText(); FileInputStream fis = null; try { KeyStore trustStore = KeyStore.getInstance(type); fis = new FileInputStream(location); if (log.isInfoEnabled()) { log.info(name + " Loading Trust Keystore from : " + location); } trustStore.load(fis, storePassword.toCharArray()); TrustManagerFactory trustManagerfactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerfactory.init(trustStore); trustManagers = trustManagerfactory.getTrustManagers(); } catch (GeneralSecurityException gse) { log.error(name + " Error loading Key store : " + location, gse); throw new AxisFault("Error loading Key store : " + location, gse); } catch (IOException ioe) { log.error(name + " Error opening Key store : " + location, ioe); throw new AxisFault("Error opening Key store : " + location, ioe); } finally { if (fis != null) { try { fis.close(); } catch (IOException ignore) { } } } } else if (novalidatecert) { if (log.isWarnEnabled()) { log.warn(name + " Server certificate validation (trust) has been disabled. " + "DO NOT USE IN PRODUCTION!"); } trustManagers = new TrustManager[] { new NoValidateCertTrustManager() }; } try { final Parameter sslpParameter = transportOut.getParameter("SSLProtocol"); final String sslProtocol = sslpParameter != null ? sslpParameter.getValue().toString() : "TLS"; SSLContext sslcontext = SSLContext.getInstance(sslProtocol); sslcontext.init(keymanagers, trustManagers, null); return sslcontext; } catch (GeneralSecurityException gse) { log.error(name + " 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:org.wso2.carbon.identity.authenticator.wikid.WiKIDAuthenticator.java
public static void setHttpsClientCert(String certificateFile, String certPassword) { try {// ww w . j av a 2 s .co m if (certificateFile == null || !new File(certificateFile).exists()) { return; } KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509"); KeyStore keyStore = KeyStore.getInstance("PKCS12"); InputStream keyInput = new FileInputStream(certificateFile); keyStore.load(keyInput, certPassword.toCharArray()); keyInput.close(); keyManagerFactory.init(keyStore, certPassword.toCharArray()); SSLContext context = SSLContext.getInstance("TLS"); context.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom()); SSLContext.setDefault(context); } catch (KeyStoreException e) { } catch (NoSuchAlgorithmException e) { } catch (FileNotFoundException e) { } catch (IOException e) { } catch (CertificateException e) { } catch (UnrecoverableKeyException e) { } catch (KeyManagementException e) { } }
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."); }/* w w w . j a v a2 s . com*/ // 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"); }