List of usage examples for javax.net.ssl TrustManagerFactory getDefaultAlgorithm
public static final String getDefaultAlgorithm()
From source file:com.photon.phresco.framework.rest.api.util.FrameworkServiceUtil.java
public static List<CertificateInfo> getCertificate(String host, int port) throws PhrescoException { List<CertificateInfo> certificates = new ArrayList<CertificateInfo>(); CertificateInfo info;/*from ww w.jav a 2 s. c om*/ try { KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); SSLContext context = SSLContext.getInstance("TLS"); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0]; SavingTrustManager tm = new SavingTrustManager(defaultTrustManager); context.init(null, new TrustManager[] { tm }, null); SSLSocketFactory factory = context.getSocketFactory(); SSLSocket socket = (SSLSocket) factory.createSocket(host, port); socket.setSoTimeout(10000); try { socket.startHandshake(); socket.close(); } catch (SSLException e) { } X509Certificate[] chain = tm.chain; for (int i = 0; i < chain.length; i++) { X509Certificate x509Certificate = chain[i]; String subjectDN = x509Certificate.getSubjectDN().getName(); String[] split = subjectDN.split(","); info = new CertificateInfo(); info.setSubjectDN(subjectDN); info.setDisplayName(split[0]); info.setCertificate(x509Certificate); certificates.add(info); } } catch (Exception e) { throw new PhrescoException(e); } return certificates; }
From source file:org.araqne.pkg.PackageManagerService.java
private String downloadString(PackageRepository repo, URL url) throws IOException, KeyStoreException, UnrecoverableKeyException, KeyManagementException { if (repo.isLocalFilesystem()) { FileInputStream stream = null; try {// w w w . j a v a 2 s . c o m File file = new File(url.toURI()); long length = file.length(); stream = new FileInputStream(file); byte[] b = new byte[(int) length]; stream.read(b); return new String(b, Charset.forName("UTF-8")); } catch (URISyntaxException e) { e.printStackTrace(); return new String(); } finally { if (stream != null) stream.close(); } } else if (repo.isHttps()) { ServiceReference<?> ref = bc.getServiceReference(KeyStoreManager.class.getName()); KeyStoreManager keyman = (KeyStoreManager) bc.getService(ref); try { TrustManagerFactory tmf = keyman.getTrustManagerFactory(repo.getTrustStoreAlias(), TrustManagerFactory.getDefaultAlgorithm()); KeyManagerFactory kmf = keyman.getKeyManagerFactory(repo.getKeyStoreAlias(), KeyManagerFactory.getDefaultAlgorithm()); HttpWagon.download(url, tmf, kmf); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return HttpWagon.downloadString(url); } else if (repo.isAuthRequired()) return HttpWagon.downloadString(url, repo.getAccount(), repo.getPassword()); return HttpWagon.downloadString(url); }
From source file:iracing.webapi.IracingWebApi.java
private void installCerts() throws Exception { String host = "members.iracing.com"; int port = 443; char[] password = CERT_STORE_PASSWORD.toCharArray(); File file = new File("jssecacerts"); if (!file.isFile()) { char seperator = File.separatorChar; File dir = new File(System.getProperty("java.home") + seperator + "lib" + seperator + "security"); file = new File(dir, "jssecacerts"); if (!file.isFile()) { file = new File(dir, "cacerts"); }//from w w w . j a va2s. co m } KeyStore ks; InputStream in = new FileInputStream(file); ks = KeyStore.getInstance(KeyStore.getDefaultType()); try { ks.load(in, password); } catch (Exception e) { } in.close(); SSLContext context = SSLContext.getInstance("TLS"); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0]; SavingTrustManager tm = new SavingTrustManager(defaultTrustManager); context.init(null, new TrustManager[] { tm }, null); SSLSocketFactory factory = context.getSocketFactory(); SSLSocket socket = null; try { socket = (SSLSocket) factory.createSocket(host, port); socket.setSoTimeout(10000); socket.startHandshake(); } catch (Exception e) { //e.printStackTrace(); } finally { if (socket != null) socket.close(); } X509Certificate[] chain = tm.chain; if (chain == null) return; MessageDigest sha1 = MessageDigest.getInstance("SHA1"); MessageDigest md5 = MessageDigest.getInstance("MD5"); for (int i = 0; i < chain.length; i++) { X509Certificate cert = chain[i]; sha1.update(cert.getEncoded()); md5.update(cert.getEncoded()); } for (int count = 0; count < chain.length; count++) { X509Certificate cert = chain[count]; String alias = host + "-" + (count + 1); ks.setCertificateEntry(alias, cert); OutputStream out = new FileOutputStream("jssecacerts"); try { ks.store(out, password); } finally { out.close(); } } }
From source file:org.wso2.extension.siddhi.store.mongodb.util.MongoTableUtils.java
private static SocketFactory extractSocketFactory(String trustStore, String trustStorePassword, String keyStore, String keyStorePassword) { TrustManager[] trustManagers; KeyManager[] keyManagers;/*ww w . ja v a2s . c o m*/ try (InputStream trustStream = new FileInputStream(trustStore)) { char[] trustStorePass = trustStorePassword.toCharArray(); KeyStore trustStoreJKS = KeyStore.getInstance(KeyStore.getDefaultType()); trustStoreJKS.load(trustStream, trustStorePass); TrustManagerFactory trustFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustFactory.init(trustStoreJKS); trustManagers = trustFactory.getTrustManagers(); } catch (FileNotFoundException e) { throw new MongoTableException("Trust store file not found for secure connections to mongodb. " + "Trust Store file path : '" + trustStore + "'.", e); } catch (IOException e) { throw new MongoTableException( "I/O Exception in creating trust store for secure connections to mongodb. " + "Trust Store file path : '" + trustStore + "'.", e); } catch (CertificateException e) { throw new MongoTableException("Certificates in the trust store could not be loaded for secure " + "connections to mongodb. Trust Store file path : '" + trustStore + "'.", e); } catch (NoSuchAlgorithmException e) { throw new MongoTableException("The algorithm used to check the integrity of the trust store cannot be " + "found. Trust Store file path : '" + trustStore + "'.", e); } catch (KeyStoreException e) { throw new MongoTableException("Exception in creating trust store, no Provider supports aKeyStoreSpi " + "implementation for the specified type. Trust Store file path : '" + trustStore + "'.", e); } try (InputStream keyStream = new FileInputStream(keyStore)) { char[] keyStorePass = keyStorePassword.toCharArray(); KeyStore keyStoreJKS = KeyStore.getInstance(KeyStore.getDefaultType()); keyStoreJKS.load(keyStream, keyStorePass); KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keyStoreJKS, keyStorePass); keyManagers = keyManagerFactory.getKeyManagers(); } catch (FileNotFoundException e) { throw new MongoTableException("Key store file not found for secure connections to mongodb. " + "Key Store file path : '" + keyStore + "'.", e); } catch (IOException e) { throw new MongoTableException( "I/O Exception in creating trust store for secure connections to mongodb. " + "Key Store file path : '" + keyStore + "'.", e); } catch (CertificateException e) { throw new MongoTableException("Certificates in the trust store could not be loaded for secure " + "connections to mongodb. Key Store file path : '" + keyStore + "'.", e); } catch (NoSuchAlgorithmException e) { throw new MongoTableException("The algorithm used to check the integrity of the trust store cannot be " + "found. Key Store file path : '" + keyStore + "'.", e); } catch (KeyStoreException e) { throw new MongoTableException( "Exception in creating trust store, no Provider supports aKeyStoreSpi " + "implementation for the specified type. Key Store file path : '" + keyStore + "'.", e); } catch (UnrecoverableKeyException e) { throw new MongoTableException( "Key in the keystore cannot be recovered. " + "Key Store file path : '" + keyStore + "'.", e); } try { SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(keyManagers, trustManagers, null); SSLContext.setDefault(sslContext); return sslContext.getSocketFactory(); } catch (KeyManagementException e) { throw new MongoTableException( "Error in validating the key in the key store/ trust store. " + "Trust Store file path : '" + trustStore + "'. " + "Key Store file path : '" + keyStore + "'.", e); } catch (NoSuchAlgorithmException e) { throw new MongoTableException( " SSL Algorithm used to create SSL Socket Factory for mongodb connections " + "is not found.", e); } }
From source file:com.sat.vcse.automation.utils.http.HttpClient.java
private TrustManager[] getTrustManagers() throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException { final InputStream truststoreis; TrustManager[] trustManager;//from w w w .j a v a2 s. com if (StringUtils.isBlank(this.truststore) || StringUtils.isBlank(this.truststorePasswd)) { //This means we dont want certificate authentication of any type, however we want only encryption during https call trustManager = new TrustManager[] { new NoOpTrustManager() }; } else { // Load the Client Truststore final TrustManagerFactory tmf = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); final KeyStore truststore = KeyStore.getInstance(KeyStore.getDefaultType()); //see if the file is present otherwise read from class path File trustStoreFile = new File(this.truststore); if (trustStoreFile.exists()) { truststoreis = new FileInputStream(trustStoreFile); } else { LogHandler.warn("File not found, so trying to read it from class path now"); truststoreis = HttpClient.class.getResourceAsStream(this.truststore); } truststore.load(truststoreis, this.truststorePasswd.toCharArray()); tmf.init(truststore); trustManager = tmf.getTrustManagers(); truststoreis.close(); } return trustManager; }
From source file:org.wildfly.security.sasl.entity.EntityTest.java
private X509TrustManager getX509TrustManager(final KeyStore trustStore) throws GeneralSecurityException, IOException { TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(trustStore); for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) { if (trustManager instanceof X509TrustManager) { return (X509TrustManager) trustManager; }/* w w w . jav a 2 s . c o m*/ } return null; }
From source file:org.deviceconnect.android.message.DevicePluginContext.java
/** * SSLContext ?????./*from www . ja va2s. c o m*/ * <p> * ? Web ?????Manager???????????SSLContext ??? * </p> * @param keyStore * @return SSLContext? * @throws GeneralSecurityException SSLContext??????? */ protected SSLContext createSSLContext(final KeyStore keyStore) throws GeneralSecurityException { SSLContext sslContext = SSLContext.getInstance("TLS"); KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keyStore, "0000".toCharArray()); TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keyStore); sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom()); return sslContext; }
From source file:me.mneri.rice.Connection.java
public void start() { if (mState != State.CLOSED) return;//from w w w .ja v a 2s. c o m mState = State.STARTED; emit(new Event(START, this)); new Thread(() -> { try { if (mSecure) { SSLContext sslContext = SSLContext.getInstance("TLS"); String algorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(algorithm); tmFactory.init((KeyStore) null); sslContext.init(null, tmFactory.getTrustManagers(), null); SSLSocketFactory sslFactory = sslContext.getSocketFactory(); SSLSocket sslSocket = (SSLSocket) sslFactory.createSocket(mHost, mPort); sslSocket.startHandshake(); mSocket = sslSocket; } else { mSocket = new Socket(mHost, mPort); } mSocket.setSoTimeout(mSoTimeout); mInputThread = new InputThread(mSocket.getInputStream(), mEncoding, new InputThreadObserver()); mInputThread.start(); OutputInterfaceFactory outFactory = OutputInterfaceFactory.instance(); OutputStreamWriter outWriter = new OutputStreamWriter(mSocket.getOutputStream(), mEncoding); mOutputInterface = outFactory.createInterface(outWriter); mState = State.CONNECTED; emit(new Event(CONNECT, this)); cap("LS"); if (!TextUtils.isEmpty(mPass)) pass(mPass); nick(mWantedNick); user(mUser, mLoginMode, "*", mReal); } catch (Exception e) { onDisconnection(); } }).start(); }
From source file:com.vmware.photon.controller.deployer.xenon.workflow.BatchCreateManagementWorkflowService.java
private void generateCertificate(DeploymentService.State deploymentState) { if (!deploymentState.oAuthEnabled) { sendStageProgressPatch(TaskStage.STARTED, TaskState.SubStage.CREATE_VMS); return;//from www . jav a2 s. c om } List<String> command = new ArrayList<>(); command.add("./" + GENERATE_CERTIFICATE_SCRIPT_NAME); command.add(deploymentState.oAuthServerAddress); command.add(deploymentState.oAuthPassword); command.add(deploymentState.oAuthTenantName); command.add(PhotonControllerXenonHost.KEYSTORE_FILE); command.add(PhotonControllerXenonHost.KEYSTORE_PASSWORD); DeployerContext deployerContext = HostUtils.getDeployerContext(this); File scriptLogFile = new File(deployerContext.getScriptLogDirectory(), GENERATE_CERTIFICATE_SCRIPT_NAME + ".log"); ScriptRunner scriptRunner = new ScriptRunner.Builder(command, deployerContext.getScriptTimeoutSec()) .directory(deployerContext.getScriptDirectory()) .redirectOutput(ProcessBuilder.Redirect.to(scriptLogFile)).build(); ListenableFutureTask<Integer> futureTask = ListenableFutureTask.create(scriptRunner); HostUtils.getListeningExecutorService(this).submit(futureTask); Futures.addCallback(futureTask, new FutureCallback<Integer>() { @Override public void onSuccess(@javax.validation.constraints.NotNull Integer result) { try { if (result != 0) { logScriptErrorAndFail(result, scriptLogFile); } else { // Set the inInstaller flag to true which would allow us to override the xenon service client to talk // to the auth enabled newly deployed management plane using https with two way SSL. ((PhotonControllerXenonHost) getHost()).setInInstaller(true); // need to switch the ssl context for the thrift clients to use // the generated certs to be able to talk to the authenticated // agents try { SSLContext sslContext = SSLContext.getInstance(KeyStoreUtils.THRIFT_PROTOCOL); TrustManagerFactory tmf = null; tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); KeyStore keyStore = KeyStore.getInstance("JKS"); InputStream in = FileUtils .openInputStream(new File(PhotonControllerXenonHost.KEYSTORE_FILE)); keyStore.load(in, PhotonControllerXenonHost.KEYSTORE_PASSWORD.toCharArray()); tmf.init(keyStore); sslContext.init(null, tmf.getTrustManagers(), null); ((PhotonControllerXenonHost) getHost()).regenerateThriftClients(sslContext); KeyStoreUtils.acceptAllCerts(KeyStoreUtils.THRIFT_PROTOCOL); } catch (Throwable t) { ServiceUtils.logSevere(BatchCreateManagementWorkflowService.this, "Regenerating the SSL Context for thrift failed, ignoring to make tests pass, it fail later"); ServiceUtils.logSevere(BatchCreateManagementWorkflowService.this, t); } sendStageProgressPatch(TaskStage.STARTED, TaskState.SubStage.CREATE_VMS); } } catch (Throwable t) { failTask(t); } } @Override public void onFailure(Throwable throwable) { failTask(throwable); } }); }
From source file:se.leap.bitmaskclient.ProviderAPI.java
private javax.net.ssl.SSLSocketFactory getProviderSSLSocketFactory() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, KeyManagementException { String provider_cert_string = preferences.getString(Provider.CA_CERT, ""); java.security.cert.Certificate provider_certificate = ConfigHelper .parseX509CertificateFromString(provider_cert_string); // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null);/*from w w w. j a v a 2s . c o m*/ keyStore.setCertificateEntry("provider_ca_certificate", provider_certificate); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); return context.getSocketFactory(); }