List of usage examples for javax.net.ssl TrustManagerFactory getDefaultAlgorithm
public static final String getDefaultAlgorithm()
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 ww w .ja va 2 s . com 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.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 ww w . j av a 2 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.wildfly.test.integration.elytron.sasl.mgmt.AbstractKerberosMgmtSaslTestBase.java
/** * Get the trust manager for {@link #CLIENT_TRUSTSTORE_FILE}. * * @return the trust manager/* www . ja v a 2 s.co m*/ */ protected static X509TrustManager getTrustManager() throws Exception { TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(loadKeyStore(CLIENT_TRUSTSTORE_FILE)); for (TrustManager current : trustManagerFactory.getTrustManagers()) { if (current instanceof X509TrustManager) { return (X509TrustManager) current; } } throw new IllegalStateException("Unable to obtain X509TrustManager."); }
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 www . j a v a2 s. c om*/ 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."); } }
From source file:com.vmware.photon.controller.core.Main.java
private static PhotonControllerXenonHost startXenonHost(PhotonControllerConfig photonControllerConfig, ThriftModule thriftModule, DeployerConfig deployerConfig, SSLContext sslContext) throws Throwable { // Values for CloudStore final HostClientFactory hostClientFactory = thriftModule.getHostClientFactory(); final AgentControlClientFactory agentControlClientFactory = thriftModule.getAgentControlClientFactory(); final NsxClientFactory nsxClientFactory = new NsxClientFactory(); // Values for Scheduler final ServerSet cloudStoreServerSet = new StaticServerSet( new InetSocketAddress(photonControllerConfig.getXenonConfig().getRegistrationAddress(), Constants.PHOTON_CONTROLLER_PORT)); final CloudStoreHelper cloudStoreHelper = new CloudStoreHelper(cloudStoreServerSet); final CloseableHttpAsyncClient httpClient; try {// ww w . j av a2 s. co m SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial((chain, authtype) -> true).build(); httpClient = HttpAsyncClientBuilder.create() .setHostnameVerifier(SSLIOSessionStrategy.ALLOW_ALL_HOSTNAME_VERIFIER).setSSLContext(sslcontext) .build(); httpClient.start(); } catch (Throwable e) { throw new RuntimeException(e); } ServerSet apiFeServerSet = new StaticServerSet(new InetSocketAddress( photonControllerConfig.getXenonConfig().getRegistrationAddress(), Constants.MANAGEMENT_API_PORT)); logger.info("Creating PhotonController Xenon Host"); final PhotonControllerXenonHost photonControllerXenonHost = new PhotonControllerXenonHost( photonControllerConfig.getXenonConfig(), hostClientFactory, agentControlClientFactory, nsxClientFactory, cloudStoreHelper, sslContext); logger.info("Created PhotonController Xenon Host"); // Set referer Uri from the xenon host, because we do not want to rely on // CloudStoreHelper's default mechanise to create referer based on local address, // because CloudStoreHelper uses InetAddress.getLocalHost() which depends on // /etc/hosts having a hostname entry, which is not always available. // This change will allow people to run this service without need to // update their /etc/hosts file. cloudStoreHelper.setRefererUri(photonControllerXenonHost.getUri()); final ConstraintChecker checker = new CloudStoreConstraintChecker(cloudStoreHelper, photonControllerXenonHost); logger.info("Creating Cloud Store Xenon Service Group"); CloudStoreServiceGroup cloudStoreServiceGroup = createCloudStoreServiceGroup(deployerConfig.isInstaller()); logger.info("Created Cloud Store Xenon Service Group"); logger.info("Registering Cloud Store Xenon Service Group"); photonControllerXenonHost.registerCloudStore(cloudStoreServiceGroup); logger.info("Registered Cloud Store Xenon Service Group"); logger.info("Creating Scheduler Xenon Service Group"); SchedulerServiceGroup schedulerServiceGroup = createSchedulerServiceGroup(photonControllerConfig.getRoot(), checker); logger.info("Created Scheduler Xenon Service Group"); logger.info("Registering Scheduler Xenon Service Group"); photonControllerXenonHost.registerScheduler(schedulerServiceGroup); logger.info("Registered Scheduler Xenon Service Group"); logger.info("Creating Housekeeper Xenon Service Group"); HousekeeperServiceGroup housekeeperServiceGroup = createHousekeeperServiceGroup(); logger.info("Created Housekeeper Xenon Service Group"); logger.info("Registering Housekeeper Xenon Service Group"); photonControllerXenonHost.registerHousekeeper(housekeeperServiceGroup); logger.info("Registered Housekeeper Xenon Service Group"); logger.info("Creating Deployer Xenon Service Group"); DeployerServiceGroup deployerServiceGroup = createDeployerServiceGroup(photonControllerConfig, deployerConfig, apiFeServerSet, cloudStoreServerSet, httpClient); logger.info("Created Deployer Xenon Service Group"); logger.info("Registering Deployer Xenon Service Group"); photonControllerXenonHost.registerDeployer(deployerServiceGroup); logger.info("Registered Deployer Xenon Service Group"); DeployerContext deployerContext = deployerConfig.getDeployerContext(); if (deployerContext.isAuthEnabled()) { ServiceClient serviceClient = NettyHttpServiceClient.create(Main.class.getSimpleName(), Executors.newFixedThreadPool(Utils.DEFAULT_THREAD_COUNT), Executors.newScheduledThreadPool(Utils.DEFAULT_IO_THREAD_COUNT), photonControllerXenonHost); /* To make sure that Xenon uses only TLSv1.2 and disallows SSLv3, TLSv1, TLSv1.1 the Docker file for the photon-controller-core container is edited. The java.security file located inside the container at the location /var/opt/OpenJDK-* /jre/lib/security has the information under the jdk.tls.disabledAlgorithms */ SSLContext clientContext = SSLContext.getInstance(ServiceClient.TLS_PROTOCOL_NAME); TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init((KeyStore) null); KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); KeyStore keyStore = KeyStore.getInstance("JKS"); try (FileInputStream fis = new FileInputStream(deployerContext.getKeyStorePath())) { keyStore.load(fis, deployerContext.getKeyStorePassword().toCharArray()); } keyManagerFactory.init(keyStore, deployerContext.getKeyStorePassword().toCharArray()); clientContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null); serviceClient.setSSLContext(clientContext); photonControllerXenonHost.setClient(serviceClient); } logger.info("Starting PhotonController Xenon Host"); photonControllerXenonHost.start(); logger.info("Started PhotonController Xenon Host"); logger.info("Creating SystemConfig instance"); SystemConfig.createInstance(photonControllerXenonHost); logger.info("Created SystemConfig instance"); return photonControllerXenonHost; }
From source file:ddf.security.realm.sts.StsRealm.java
/** * Setup trust store for SSL client./*from www .ja va2 s .c o m*/ */ private void setupTrustStore(TLSClientParameters tlsParams, String trustStorePath, String trustStorePassword) { File trustStoreFile = new File(trustStorePath); if (trustStoreFile.exists() && trustStorePassword != null) { KeyStore trustStore = null; FileInputStream fis = null; try { trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); fis = new FileInputStream(trustStoreFile); LOGGER.debug("Loading trustStore"); trustStore.load(fis, trustStorePassword.toCharArray()); TrustManagerFactory trustFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustFactory.init(trustStore); LOGGER.debug("trust manager factory initialized"); TrustManager[] tm = trustFactory.getTrustManagers(); tlsParams.setTrustManagers(tm); } catch (FileNotFoundException e) { LOGGER.error("Unable to find SSL store: " + trustStorePath, e); } catch (IOException e) { LOGGER.error("Unable to load trust store. " + trustStore, e); } catch (CertificateException e) { LOGGER.error("Unable to load certificates from trust store. " + trustStore, e); } catch (KeyStoreException e) { LOGGER.error("Unable to read trust store: ", e); } catch (NoSuchAlgorithmException e) { LOGGER.error("Problems creating SSL socket. Usually this is " + "referring to the certificate sent by the server not being trusted by the client.", e); } finally { IOUtils.closeQuietly(fis); } } }
From source file:ddf.security.sts.claimsHandler.ClaimsHandlerManager.java
public static TrustManagerFactory createTrustManagerFactory(String trustStoreLoc, String trustStorePass) throws IOException { TrustManagerFactory tmf;/*from w ww. j ava 2 s . c o m*/ try { // truststore stuff KeyStore trustStore = KeyStore.getInstance(System.getProperty("javax.net.ssl.keyStoreType")); LOGGER.debug("trustStoreLoc = {}", trustStoreLoc); FileInputStream trustFIS = new FileInputStream(trustStoreLoc); try { LOGGER.debug("Loading trustStore"); trustStore.load(trustFIS, trustStorePass.toCharArray()); } catch (CertificateException e) { throw new IOException("Unable to load certificates from truststore. " + trustStoreLoc, e); } finally { IOUtils.closeQuietly(trustFIS); } tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(trustStore); LOGGER.debug("trust 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 (KeyStoreException e) { throw new IOException("Unable to read keystore. " + trustStoreLoc, e); } return tmf; }
From source file:com.liferay.sync.engine.lan.session.LanSession.java
private static SSLConnectionSocketFactory _getSSLSocketFactory() throws Exception { KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, null);//w ww. ja v a 2s. c o m for (SyncAccount syncAccount : SyncAccountService.findAll()) { if (!syncAccount.isActive() || !syncAccount.isLanEnabled()) { continue; } try { PrivateKey privateKey = LanPEMParserUtil.parsePrivateKey(syncAccount.getLanKey()); if (privateKey == null) { _logger.error("SyncAccount {} missing valid private key", syncAccount.getSyncAccountId()); continue; } X509Certificate x509Certificate = LanPEMParserUtil .parseX509Certificate(syncAccount.getLanCertificate()); if (x509Certificate == null) { _logger.error("SyncAccount {} missing valid certificate", syncAccount.getSyncAccountId()); continue; } keyStore.setCertificateEntry(syncAccount.getLanServerUuid(), x509Certificate); keyStore.setKeyEntry(syncAccount.getLanServerUuid(), privateKey, "".toCharArray(), new Certificate[] { x509Certificate }); } catch (Exception e) { _logger.error(e.getMessage(), e); } } KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keyStore, "".toCharArray()); TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keyStore); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null); return new SNISSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier()); }
From source file:org.kuali.kra.s2s.service.impl.GrantsGovConnectorServiceImpl.java
/** * This method is to confgiure KeyStore and Truststore for Grants.Gov webservice client * @param tlsConfig/*www. j a v a 2 s.c o m*/ * @param alias * @param mulitCampusEnabled * @throws S2SException */ protected void configureKeyStoreAndTrustStore(TLSClientParameters tlsConfig, String alias, boolean mulitCampusEnabled) throws S2SException { KeyStore keyStore = S2SCertificateReader.getKeyStore(); KeyManagerFactory keyManagerFactory; try { keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); if (alias != null && mulitCampusEnabled) { KeyStore keyStoreAlias; keyStoreAlias = KeyStore.getInstance(JKS_TYPE); Certificate[] certificates = keyStore.getCertificateChain(alias); Key key = keyStore.getKey(alias, s2SUtilService.getProperty(KEYSTORE_PASSWORD).toCharArray()); keyStoreAlias.load(null, null); keyStoreAlias.setKeyEntry(alias, key, s2SUtilService.getProperty(KEYSTORE_PASSWORD).toCharArray(), certificates); keyManagerFactory.init(keyStoreAlias, s2SUtilService.getProperty(KEYSTORE_PASSWORD).toCharArray()); } else { keyManagerFactory.init(keyStore, s2SUtilService.getProperty(KEYSTORE_PASSWORD).toCharArray()); } KeyManager[] km = keyManagerFactory.getKeyManagers(); tlsConfig.setKeyManagers(km); KeyStore trustStore = S2SCertificateReader.getTrustStore(); TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(trustStore); TrustManager[] tm = trustManagerFactory.getTrustManagers(); tlsConfig.setTrustManagers(tm); } catch (NoSuchAlgorithmException e) { LOG.error(e); throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage()); } catch (KeyStoreException e) { LOG.error(e); throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage()); } catch (UnrecoverableKeyException e) { LOG.error(e); throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage()); } catch (CertificateException e) { LOG.error(e); throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage()); } catch (IOException e) { LOG.error(e); throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage()); } }