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.apache.geode.management.internal.cli.commands.ConnectCommand.java
private KeyManager[] getKeyManagers(SSLConfig sslConfig) throws Exception { FileInputStream keyStoreStream = null; KeyManagerFactory keyManagerFactory = null; try {//from w w w.j a va 2 s.c o m if (StringUtils.isNotBlank(sslConfig.getKeystore())) { KeyStore clientKeys = KeyStore.getInstance(sslConfig.getKeystoreType()); keyStoreStream = new FileInputStream(sslConfig.getKeystore()); clientKeys.load(keyStoreStream, sslConfig.getKeystorePassword().toCharArray()); keyManagerFactory = KeyManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(clientKeys, sslConfig.getKeystorePassword().toCharArray()); } } finally { if (keyStoreStream != null) { keyStoreStream.close(); } } return keyManagerFactory != null ? keyManagerFactory.getKeyManagers() : null; }
From source file:com.gamesalutes.utils.EncryptUtils.java
/** * Creates an <code>SSLContext</code> that uses the specified trusted certificates. * /*from ww w .ja va 2 s .c om*/ * @param protocol the {@link TransportSecurityProtocol} to use for the context * @param trustedCerts certificates to import into the <code>SSLContext</code> or <code>null</code> * to accept all issuers * @param privateKey the client key to authenticate the client with the server * @return the created <code>SSLContext</code> * @throws Exception if error occurs during the process of creating the context */ public static SSLContext createSSLContext(TransportSecurityProtocol protocol, PrivateKey privateKey, java.security.cert.X509Certificate... trustedCerts) throws Exception { if (trustedCerts != null && trustedCerts.length == 0) throw new IllegalArgumentException("trustedCerts is empty"); X509TrustManager defaultManager = null; KeyManager[] keyManagers = null; KeyStore keyStore = null; if (privateKey != null || trustedCerts != null) { // create a new key store instance that will install the certificates // and/or the private keys keyStore = KeyStore.getInstance(JKS_TYPE); keyStore.load(null, null); } // import the certs if (trustedCerts != null) { // set up the key manager for the certificates javax.net.ssl.TrustManagerFactory trustFact = javax.net.ssl.TrustManagerFactory .getInstance(KEY_MANAGEMENT_ALG_SUN_X509); // install the certificates in the key store and give them a unique alias int imported = 0; for (java.security.cert.X509Certificate cert : trustedCerts) { if (cert != null) keyStore.setCertificateEntry("cert" + ++imported, cert); } if (imported == 0) throw new IllegalArgumentException("no non-null certs in trustedCerts"); // add the certs to the trust factory trustFact.init(keyStore); // get a default trust manager TrustManager[] tms = trustFact.getTrustManagers(); if (tms != null && tms.length >= 1) defaultManager = (X509TrustManager) tms[0]; } // import the private key if (privateKey != null) { keyStore.setKeyEntry("client", privateKey, null, null); KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(privateKey.getAlgorithm()); kmfactory.init(keyStore, null); keyManagers = kmfactory.getKeyManagers(); } //create the SSL context based on these parameters SSLContext sslContext = SSLContext.getInstance(protocol.toString()); // use a CertX509TrustManager since default one will still fail validation for // self-signed certs sslContext.init(keyManagers, new TrustManager[] { trustedCerts != null ? new CertX509TrustManager(defaultManager, trustedCerts) : new CertX509TrustManager() }, null); return sslContext; }
From source file:org.codice.ddf.cxf.client.impl.SecureCxfClientFactoryImpl.java
@SuppressWarnings("squid:S3776") private void configureConduit(ClientConfiguration clientConfig) { HTTPConduit httpConduit = clientConfig.getHttpConduit(); if (httpConduit == null) { LOGGER.info("HTTPConduit was null for {}. Unable to configure security.", this); return;//from w ww . jav a2 s .c om } if (allowRedirects) { HTTPClientPolicy clientPolicy = httpConduit.getClient(); if (clientPolicy != null) { clientPolicy.setAutoRedirect(true); Bus bus = clientConfig.getBus(); if (bus != null) { bus.getProperties().put(AUTO_REDIRECT_ALLOW_REL_URI, true); bus.getProperties().put(AUTO_REDIRECT_MAX_SAME_URI_COUNT, getSameUriRedirectMax()); } } } TLSClientParameters tlsParams = httpConduit.getTlsClientParameters(); if (tlsParams == null) { tlsParams = new TLSClientParameters(); } tlsParams.setDisableCNCheck(disableCnCheck); tlsParams.setUseHttpsURLConnectionDefaultHostnameVerifier(!disableCnCheck); String cipherSuites = System.getProperty("https.cipherSuites"); if (cipherSuites != null) { tlsParams.setCipherSuites(Arrays.asList(cipherSuites.split(","))); } KeyStore keyStore = null; KeyStore trustStore = null; try { keyStore = SecurityConstants.newKeystore(); trustStore = SecurityConstants.newTruststore(); } catch (KeyStoreException e) { LOGGER.debug("Unable to create keystore instance of type {}", System.getProperty(SecurityConstants.KEYSTORE_TYPE), e); } Path keyStoreFile; if (keyInfo != null && StringUtils.isNotBlank(keyInfo.getKeystorePath())) { keyStoreFile = Paths.get(keyInfo.getKeystorePath()); } else { keyStoreFile = Paths.get(SecurityConstants.getKeystorePath()); } Path trustStoreFile = Paths.get(SecurityConstants.getTruststorePath()); String ddfHome = System.getProperty("ddf.home"); if (ddfHome != null) { Path ddfHomePath = Paths.get(ddfHome); if (!keyStoreFile.isAbsolute()) { keyStoreFile = Paths.get(ddfHomePath.toString(), keyStoreFile.toString()); } if (!trustStoreFile.isAbsolute()) { trustStoreFile = Paths.get(ddfHomePath.toString(), trustStoreFile.toString()); } } String keyStorePassword = SecurityConstants.getKeystorePassword(); String trustStorePassword = SecurityConstants.getTruststorePassword(); if (!Files.isReadable(keyStoreFile) || !Files.isReadable(trustStoreFile)) { LOGGER.debug("Unable to read system key/trust store files: [ {} ] [ {} ]", keyStoreFile, trustStoreFile); return; } try (InputStream kfis = Files.newInputStream(keyStoreFile)) { if (keyStore != null) { keyStore.load(kfis, keyStorePassword.toCharArray()); } } catch (NoSuchAlgorithmException | CertificateException | IOException e) { LOGGER.debug("Unable to load system key file.", e); } try (InputStream tfis = Files.newInputStream(trustStoreFile)) { if (trustStore != null) { trustStore.load(tfis, trustStorePassword.toCharArray()); } } catch (NoSuchAlgorithmException | CertificateException | IOException e) { LOGGER.debug("Unable to load system trust file.", e); } KeyManager[] keyManagers = null; try { KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keyStore, keyStorePassword.toCharArray()); keyManagers = keyManagerFactory.getKeyManagers(); tlsParams.setKeyManagers(keyManagers); } catch (NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException e) { LOGGER.debug("Unable to initialize KeyManagerFactory.", e); } TrustManager[] trustManagers = null; try { TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(trustStore); trustManagers = trustManagerFactory.getTrustManagers(); tlsParams.setTrustManagers(trustManagers); } catch (NoSuchAlgorithmException | KeyStoreException e) { LOGGER.debug("Unable to initialize TrustManagerFactory.", e); } if (keyInfo != null) { LOGGER.trace("Using keystore file: {}, alias: {}", keyStoreFile, keyInfo.getAlias()); tlsParams.setUseHttpsURLConnectionDefaultSslSocketFactory(false); tlsParams.setCertAlias(keyInfo.getAlias()); try { if (keyManagers == null) { throw new KeyManagementException("keyManagers was null"); } boolean validProtocolFound = false; String validProtocolsStr = System.getProperty("jdk.tls.client.protocols"); if (StringUtils.isNotBlank(validProtocolsStr)) { String[] validProtocols = validProtocolsStr.split(","); for (String validProtocol : validProtocols) { if (validProtocol.equals(sslProtocol)) { validProtocolFound = true; break; } } if (!validProtocolFound) { LOGGER.error("{} is not in list of valid SSL protocols {}", sslProtocol, validProtocolsStr); } } else { validProtocolFound = true; } if (validProtocolFound) { tlsParams.setSSLSocketFactory( getSSLSocketFactory(sslProtocol, keyInfo.getAlias(), keyManagers, trustManagers)); } } catch (KeyManagementException | NoSuchAlgorithmException e) { LOGGER.debug("Unable to override default SSL Socket Factory", e); } } else { tlsParams.setUseHttpsURLConnectionDefaultSslSocketFactory(true); tlsParams.setCertAlias(SystemBaseUrl.INTERNAL.getHost()); } httpConduit.setTlsClientParameters(tlsParams); }
From source file:org.apache.cassandra.hadoop.cql3.CqlConfigHelper.java
private static SSLContext getSSLContext(String truststorePath, String truststorePassword, String keystorePath, String keystorePassword) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException, UnrecoverableKeyException, KeyManagementException { SSLContext ctx;// w w w .ja va2 s . co m try (FileInputStream tsf = new FileInputStream(truststorePath); FileInputStream ksf = new FileInputStream(keystorePath)) { 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.parosproxy.paros.network.SSLConnector.java
public SSLSocketFactory getTunnelSSLSocketFactory(String hostname) { // SSLServerSocketFactory ssf = null; // set up key manager to do server authentication // KeyStore ks; try {//from ww w . j a v a 2s . c o m SSLContext ctx = SSLContext.getInstance(SSL); // Normally "SunX509", "IbmX509"... KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); SslCertificateService scs = CachedSslCertifificateServiceImpl.getService(); KeyStore ks = scs.createCertForHost(hostname); kmf.init(ks, SslCertificateService.PASSPHRASE); java.security.SecureRandom x = new java.security.SecureRandom(); x.setSeed(System.currentTimeMillis()); ctx.init(kmf.getKeyManagers(), null, x); SSLSocketFactory tunnelSSLFactory = createDecoratedServerSslSocketFactory(ctx.getSocketFactory()); return tunnelSSLFactory; } catch (NoSuchAlgorithmException | KeyStoreException | CertificateException | UnrecoverableKeyException | KeyManagementException | InvalidKeyException | NoSuchProviderException | SignatureException | IOException e) { // Turn into RuntimeException. How to handle this error in a user // friendly way? throw new RuntimeException(e); } }
From source file:com.datastax.loader.CqlDelimLoad.java
private SSLOptions createSSLOptions() throws KeyStoreException, FileNotFoundException, IOException, NoSuchAlgorithmException, KeyManagementException, CertificateException, UnrecoverableKeyException { TrustManagerFactory tmf = null; KeyStore tks = KeyStore.getInstance("JKS"); tks.load((InputStream) new FileInputStream(new File(truststorePath)), truststorePwd.toCharArray()); tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(tks);//from w ww. j a va2s.c o m KeyManagerFactory kmf = null; if (null != keystorePath) { KeyStore kks = KeyStore.getInstance("JKS"); kks.load((InputStream) new FileInputStream(new File(keystorePath)), keystorePwd.toCharArray()); kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(kks, keystorePwd.toCharArray()); } SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(kmf != null ? kmf.getKeyManagers() : null, tmf != null ? tmf.getTrustManagers() : null, new SecureRandom()); return JdkSSLOptions.builder().withSSLContext(sslContext).build(); }
From source file:org.apache.nifi.controller.livy.LivySessionController.java
private void setSslSocketFactory(HttpsURLConnection httpsURLConnection, SSLContextService sslService, SSLContext sslContext) throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException, KeyManagementException { final String keystoreLocation = sslService.getKeyStoreFile(); final String keystorePass = sslService.getKeyStorePassword(); final String keystoreType = sslService.getKeyStoreType(); // prepare the keystore final KeyStore keyStore = KeyStore.getInstance(keystoreType); try (FileInputStream keyStoreStream = new FileInputStream(keystoreLocation)) { keyStore.load(keyStoreStream, keystorePass.toCharArray()); }//from ww w. ja v a2s .c o m final KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keyStore, keystorePass.toCharArray()); // load truststore final String truststoreLocation = sslService.getTrustStoreFile(); final String truststorePass = sslService.getTrustStorePassword(); final String truststoreType = sslService.getTrustStoreType(); KeyStore truststore = KeyStore.getInstance(truststoreType); final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("X509"); truststore.load(new FileInputStream(truststoreLocation), truststorePass.toCharArray()); trustManagerFactory.init(truststore); sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null); final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); httpsURLConnection.setSSLSocketFactory(sslSocketFactory); }
From source file:org.wso2.carbon.device.mgt.jaxrs.service.impl.admin.DeviceAnalyticsArtifactUploaderAdminServiceImpl.java
/** * Initializes the SSL Context/*from w ww . j a v a 2s . c o m*/ */ private void initSSLConnection() throws NoSuchAlgorithmException, UnrecoverableKeyException, KeyStoreException, KeyManagementException { KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KEY_MANAGER_TYPE); keyManagerFactory.init(keyStore, keyStorePassword); TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TRUST_MANAGER_TYPE); trustManagerFactory.init(trustStore); // Create and initialize SSLContext for HTTPS communication sslContext = SSLContext.getInstance(SSLV3); sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null); SSLContext.setDefault(sslContext); }
From source file:org.mule.transport.ldap.util.DSManager.java
public static IoFilterChainBuilder init(final KeyStore ks) throws NamingException { SSLContext sslCtx;/*from w w w.j a v a2s . co m*/ try { // Set up key manager factory to use our key store String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm"); if (algorithm == null) { algorithm = "SunX509"; } final KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm); kmf.init(ks, "changeit".toCharArray()); // Initialize the SSLContext to work with our key managers. sslCtx = SSLContext.getInstance("TLS"); sslCtx.init(kmf.getKeyManagers(), new TrustManager[] { new ServerX509TrustManager() }, new SecureRandom()); logger.debug("ssl set"); } catch (final Exception e) { throw (NamingException) new NamingException("Failed to create a SSL context.").initCause(e); } final DefaultIoFilterChainBuilder chain = new DefaultIoFilterChainBuilder(); chain.addLast("sslFilter", new SSLFilter(sslCtx)); return chain; }