public static SSLContext createSSLContext( boolean clientMode, String keystore, String password, String trustStore, String trustPassword) throws Exception { // Create/initialize the SSLContext with key material char[] passphrase = password.toCharArray(); // First initialize the key and trust material. KeyStore ks = KeyStore.getInstance("JKS"); ks.load(new FileInputStream(keystore), passphrase); SSLContext sslContext = SSLContext.getInstance("TLS"); if (clientMode) { // TrustManager's decide whether to allow connections. TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); sslContext.init(null, tmf.getTrustManagers(), null); } else { // KeyManager's decide which key material to use. KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(ks, passphrase); if (trustStore != null) { KeyStore ts = KeyStore.getInstance("JKS"); ts.load(new FileInputStream(trustStore), trustPassword.toCharArray()); TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); tmf.init(ts); System.out.println("Using the trust store for client auth"); sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); } else sslContext.init(kmf.getKeyManagers(), null, null); } return sslContext; }
/** * Create a new BeeswaxServiceImpl. * * @param dtHost The Hue host (ip or hostname). * @param dtPort The port Desktop runs on. * @param dtHttps Whether Desktop is running https. */ public BeeswaxServiceImpl(String dtHost, int dtPort, boolean dtHttps) { LogContext.initLogCapture(); this.executor = Executors.newCachedThreadPool(new NamingThreadFactory("Beeswax-%d")); this.runningQueries = new ConcurrentHashMap<String, RunningQueryState>(); String protocol; if (dtHttps) { protocol = "https"; try { // Disable SSL verification. HUE cert may be signed by untrusted CA. SSLContext sslcontext = SSLContext.getInstance("SSL"); sslcontext.init( null, new DummyX509TrustManager[] {new DummyX509TrustManager()}, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sslcontext.getSocketFactory()); } catch (NoSuchAlgorithmException ex) { LOG.warn("Failed to disable SSL certificate check " + ex); } catch (KeyManagementException ex) { LOG.warn("Failed to disable SSL certificate check " + ex); } DummyHostnameVerifier dummy = new DummyHostnameVerifier(); HttpsURLConnection.setDefaultHostnameVerifier(dummy); } else { protocol = "http"; } this.notifyUrl = protocol + "://" + dtHost + ":" + dtPort + NOTIFY_URL_BASE; // A daemon thread that periodically evict stale RunningQueryState objects Thread evicter = new Thread( new Runnable() { @Override public void run() { while (true) { long now = System.currentTimeMillis(); for (Map.Entry<String, RunningQueryState> entry : runningQueries.entrySet()) { RunningQueryState rqState = entry.getValue(); if (rqState.getAtime() + RUNNING_QUERY_LIFETIME < now) { String id = entry.getKey(); runningQueries.remove(id); LOG.debug("Removed " + rqState.toString()); Thread.yield(); // be nice } } LogContext.garbageCollect(RUNNING_QUERY_LIFETIME); long wakeup = now + EVICTION_INTERVAL; while (System.currentTimeMillis() < wakeup) { try { Thread.sleep(EVICTION_INTERVAL); } catch (InterruptedException e) { } } } } }, "Evicter"); evicter.setDaemon(true); evicter.start(); }
/** * HttpUrlConnection 方式,支持指定load-der.crt证书验证,此种方式Android官方建议 * * @throws CertificateException * @throws IOException * @throws KeyStoreException * @throws NoSuchAlgorithmException * @throws KeyManagementException */ public void initSSL() throws CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException { CertificateFactory cf = CertificateFactory.getInstance("X.509"); InputStream in = getAssets().open("load-der.crt"); Certificate ca = cf.generateCertificate(in); KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); keystore.load(null, null); keystore.setCertificateEntry("ca", ca); 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); URL url = new URL("https://trade3.guosen.com.cn/mtrade/check_version"); HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection(); urlConnection.setSSLSocketFactory(context.getSocketFactory()); InputStream input = urlConnection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8")); StringBuffer result = new StringBuffer(); String line = ""; while ((line = reader.readLine()) != null) { result.append(line); } Log.e("TTTT", result.toString()); }
public void init(Properties properties) throws Exception { KeyStore ks = KeyStore.getInstance("JKS"); KeyStore ts = KeyStore.getInstance("JKS"); String keyStorePassword = properties.getProperty("keyStorePassword"); if (keyStorePassword == null) { keyStorePassword = System.getProperty("javax.net.ssl.keyStorePassword"); } String keyStore = properties.getProperty("keyStore"); if (keyStore == null) { keyStore = System.getProperty("javax.net.ssl.keyStore"); } if (keyStore == null || keyStorePassword == null) { throw new RuntimeException("SSL is enabled but keyStore[Password] properties aren't set!"); } String keyManagerAlgorithm = getProperty(properties, "keyManagerAlgorithm", "SunX509"); String trustManagerAlgorithm = getProperty(properties, "trustManagerAlgorithm", "SunX509"); String protocol = getProperty(properties, "protocol", "TLS"); final char[] passPhrase = keyStorePassword.toCharArray(); final String keyStoreFile = keyStore; ks.load(new FileInputStream(keyStoreFile), passPhrase); ts.load(new FileInputStream(keyStoreFile), passPhrase); KeyManagerFactory kmf = KeyManagerFactory.getInstance(keyManagerAlgorithm); kmf.init(ks, passPhrase); TrustManagerFactory tmf = TrustManagerFactory.getInstance(trustManagerAlgorithm); tmf.init(ts); sslContext = SSLContext.getInstance(protocol); sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); }
private SSLSocketFactory createTrustedSocketFactory() { try { final SSLContext context = SSLContext.getInstance("ssl"); final X509TrustManager trustManager = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {} public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {} public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } }; context.init(null, new TrustManager[] {trustManager}, null); return context.getSocketFactory(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } return null; }
// ========================================================================================================= // HTTPS handling private HttpServer createHttpsServer( InetSocketAddress pSocketAddress, JolokiaServerConfig pConfig) { // initialise the HTTPS server try { HttpsServer server = HttpsServer.create(pSocketAddress, pConfig.getBacklog()); SSLContext sslContext = SSLContext.getInstance(pConfig.getSecureSocketProtocol()); // initialise the keystore KeyStore ks = getKeyStore(pConfig); // setup the key manager factory KeyManagerFactory kmf = getKeyManagerFactory(pConfig); kmf.init(ks, pConfig.getKeystorePassword()); // setup the trust manager factory TrustManagerFactory tmf = getTrustManagerFactory(pConfig); tmf.init(ks); // setup the HTTPS context and parameters sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); // Update the config to filter out bad protocols or ciphers pConfig.updateHTTPSSettingsFromContext(sslContext); server.setHttpsConfigurator(new JolokiaHttpsConfigurator(sslContext, pConfig)); return server; } catch (GeneralSecurityException e) { throw new IllegalStateException("Cannot use keystore for https communication: " + e, e); } catch (IOException e) { throw new IllegalStateException("Cannot open keystore for https communication: " + e, e); } }
@BeforeClass public static void beforeClass() throws Exception { TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(X509Certificate[] certs, String authType) {} @Override public void checkServerTrusted(X509Certificate[] certs, String authType) {} } }; SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); HostnameVerifier allHostsValid = new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }; HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid); }
@Before public void startServer() throws NoSuchAlgorithmException, KeyManagementException, IOException { server = server() .withHttpsEnabled() .usingDatabaseDir(folder.cleanDirectory(name.getMethodName()).getAbsolutePath()) .build(); httpsUri = server.httpsUri().toASCIIString(); // Because we are generating a non-CA-signed certificate, we need to turn off verification in // the client. // This is ironic, since there is no proper verification on the CA side in the first place, but // I digress. TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {} public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {} public X509Certificate[] getAcceptedIssuers() { return null; } } }; // Install the all-trusting trust manager SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, trustAllCerts, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); }
private static SSLContext sslContext(String keystoreFile, String password) throws GeneralSecurityException, IOException { KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); InputStream in = new FileInputStream(keystoreFile); try { keystore.load(in, password.toCharArray()); } finally { Util.closeQuietly(in); } KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keystore, password.toCharArray()); TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keystore); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init( keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom()); return sslContext; }
public static HttpClient wrapClient(HttpClient base) { try { SSLContext ctx = SSLContext.getInstance("TLS"); X509TrustManager tm = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {} public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {} public X509Certificate[] getAcceptedIssuers() { return null; } }; ctx.init(null, new TrustManager[] {tm}, null); SSLSocketFactory ssf = new SSLSocketFactory(ctx); ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); ClientConnectionManager ccm = base.getConnectionManager(); SchemeRegistry sr = ccm.getSchemeRegistry(); sr.register(new Scheme("https", ssf, 443)); return new DefaultHttpClient(ccm, base.getParams()); } catch (Exception ex) { return null; } }
private static SSLSocketFactory getAllHostsValidSocketFactory() throws NoSuchAlgorithmException, KeyManagementException { if (sAllHostsValidSocketFactory == null) { TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(X509Certificate[] certs, String authType) {} @Override public void checkServerTrusted(X509Certificate[] certs, String authType) {} } }; SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); sAllHostsValidSocketFactory = sc.getSocketFactory(); } return sAllHostsValidSocketFactory; }
@Override public HttpDownloadResult postUrlUnsecure( final URL url, final Integer timeOut, final Map<String, String> data, final HttpHeader httpHeader) throws HttpDownloaderException { final TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManagerAllowAll()}; final SSLSocketFactory orgSSLSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory(); final HostnameVerifier orgHostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier(); try { final SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); final HostnameVerifier hv = new HostnameVerifierAllowAll(); HttpsURLConnection.setDefaultHostnameVerifier(hv); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); return postUrlSecure(url, timeOut, data, httpHeader); } catch (final NoSuchAlgorithmException e) { logger.error("NoSuchAlgorithmException", e); throw new HttpDownloaderException("NoSuchAlgorithmException", e); } catch (final KeyManagementException e) { logger.error("KeyManagementException", e); throw new HttpDownloaderException("KeyManagementException", e); } finally { HttpsURLConnection.setDefaultHostnameVerifier(orgHostnameVerifier); HttpsURLConnection.setDefaultSSLSocketFactory(orgSSLSocketFactory); } }
private HttpUtils(Context context) { // private constructor to prevent instantiation this.context = context; try { // get version number to be set as part of user agent string version = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName; } catch (NameNotFoundException e) { } if (Utils.DEV_ENV) { HttpsURLConnection.setDefaultHostnameVerifier( new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); try { TrustManager[] trustManagers = new X509TrustManager[1]; trustManagers[0] = new TrustAllManager(); SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustManagers, null); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (Exception ex) { } } enableHttpResponseCache(); }
public static SSLParams getSslSocketFactory( InputStream[] certificates, InputStream bksFile, String password) { SSLParams sslParams = new SSLParams(); try { TrustManager[] trustManagers = prepareTrustManager(certificates); KeyManager[] keyManagers = prepareKeyManager(bksFile, password); SSLContext sslContext = SSLContext.getInstance("TLS"); X509TrustManager trustManager = null; if (trustManagers != null) { trustManager = new MyTrustManager(chooseTrustManager(trustManagers)); } else { trustManager = new UnSafeTrustManager(); } sslContext.init(keyManagers, new TrustManager[] {trustManager}, null); sslParams.sSLSocketFactory = sslContext.getSocketFactory(); sslParams.trustManager = trustManager; return sslParams; } catch (NoSuchAlgorithmException e) { throw new AssertionError(e); } catch (KeyManagementException e) { throw new AssertionError(e); } catch (KeyStoreException e) { throw new AssertionError(e); } }
/** * Default connect method connects the TCP stream, setting up SSL if necessary. * * @throws SocketException * @throws KeyManagementException * @throws IOException * @throws NoSuchAlgorithmException */ protected void connect() throws SocketException, KeyManagementException, IOException, NoSuchAlgorithmException { if (ssl) { TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted( java.security.cert.X509Certificate[] certs, String authType) {} public void checkServerTrusted( java.security.cert.X509Certificate[] certs, String authType) {} } }; // Let us create the factory where we can set some parameters for the connection SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); connection = sc.getSocketFactory().createSocket(host, port); } else { connection = new Socket(host, port); } connection.setSoTimeout(10000); // Ten second timeout sout = connection.getOutputStream(); sin = connection.getInputStream(); }
private static SocketFactory getSSLSocketFactory() { SocketFactory sslSocketFactory; try { final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {} @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {} } }; final SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustAllCerts, new java.security.SecureRandom()); // Create an ssl socket factory with our all-trusting manager sslSocketFactory = sslContext.getSocketFactory(); return sslSocketFactory; } catch (Exception ex) { logger.warn( "Unable to build ssl socket factory without certificate validation, using default instead.", ex); } return SSLSocketFactory.getDefault(); }
private static HttpClient getHttpClient() { try { SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init( null, new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) {} public void checkServerTrusted(X509Certificate[] certs, String authType) {} } }, new SecureRandom()); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); HttpClient httpClient = HttpClientBuilder.create().setSSLSocketFactory(socketFactory).build(); return httpClient; } catch (Exception e) { e.printStackTrace(); return HttpClientBuilder.create().build(); } }
protected void init(KeystoreConfig keystoreConfig, boolean acceptUnverifiedCertificates) throws KeyStoreException, IOException, NoSuchAlgorithmException, KeyManagementException { KeystoreManager keystoreMgr = KeystoreManager.getKeystoreManager(); KeyStore trustStore = keystoreMgr.getKeyStore(keystoreConfig); KeyManagerFactory keyManagerFactory = getKeyManagerFactory(trustStore, keystoreConfig.getFilePassword()); TrustManagerFactory trustManagerFactory = getTrustManagerFactory(trustStore); X509TrustManager defaultTrustManager = (X509TrustManager) trustManagerFactory.getTrustManagers()[0]; X509TrustManager customTrustManager = keystoreMgr.getCustomTrustManager( defaultTrustManager, keystoreConfig, acceptUnverifiedCertificates, trustStore); sslContext = SSLContext.getInstance(getSecurityProtocol()); sslContext.init( keyManagerFactory.getKeyManagers(), new TrustManager[] {customTrustManager}, new SecureRandom()); // XXX Should we use ALLOW_ALL_HOSTNAME_VERIFIER (least restrictive) or // BROWSER_COMPATIBLE_HOSTNAME_VERIFIER (moderate restrictive) or // STRICT_HOSTNAME_VERIFIER (most restrictive)??? sslSocketFactory = new SSLSocketFactory(sslContext, getHostnameVerifier()); }
private static void setURLConnectionTrust() { try { HttpsURLConnection.setDefaultHostnameVerifier( new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }); SSLContext context = SSLContext.getInstance("TLS"); context.init( null, new X509TrustManager[] { new X509TrustManager() { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {} public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {} public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; // return null; } } }, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory()); } catch (Exception e) { // should never happen Log.e("httpmon", "error setting up SSL trust", e); } }
/** * Used to get the base ssl context in which to create the server socket. This is basically just * so we can have a custom location for key stores. */ public SSLContext getSSLContext(String keyStoreName, String password) throws IOException { try { // Check the key manager factory KeyManagerFactory kmf = KeyManagerFactory.getInstance(this.keyManagerType); File ksFile = new File(keyStoreName); if (!ksFile.exists() || !ksFile.isFile()) throw new WinstoneException( SSL_RESOURCES.getString("HttpsListener.KeyStoreNotFound", ksFile.getPath())); InputStream in = new FileInputStream(ksFile); char[] passwordChars = password == null ? null : password.toCharArray(); KeyStore ks = KeyStore.getInstance("JKS"); ks.load(in, passwordChars); kmf.init(ks, passwordChars); Logger.log(Logger.FULL_DEBUG, SSL_RESOURCES, "HttpsListener.KeyCount", ks.size() + ""); for (Enumeration e = ks.aliases(); e.hasMoreElements(); ) { String alias = (String) e.nextElement(); Logger.log( Logger.FULL_DEBUG, SSL_RESOURCES, "HttpsListener.KeyFound", new String[] {alias, ks.getCertificate(alias) + ""}); } SSLContext context = SSLContext.getInstance("SSL"); context.init(kmf.getKeyManagers(), null, null); Arrays.fill(passwordChars, 'x'); return context; } catch (IOException err) { throw err; } catch (Throwable err) { throw new WinstoneException( SSL_RESOURCES.getString("HttpsListener.ErrorGettingContext"), err); } }
/** Initialize trust manager- does no checking, accepts all certificates */ private void initTrustManager() throws KeyManagementException { // Create a new TrustManager that accepts all certificates TRUST_MANAGER = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted( java.security.cert.X509Certificate[] certs, String authType) {} public void checkServerTrusted( java.security.cert.X509Certificate[] certs, String authType) {} } }; SSLContext sc; try { sc = SSLContext.getInstance("SSL"); sc.init(null, TRUST_MANAGER, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (NoSuchAlgorithmException e) { logger.error("Error configuring SSL", e); } }
public static void main(String[] args) { new ObjectItemGui(); // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted( java.security.cert.X509Certificate[] certs, String authType) {} public void checkServerTrusted( java.security.cert.X509Certificate[] certs, String authType) {} } }; // Install the all-trusting trust manager try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (Exception e) { } }
/** * HttpUrlConnection支持所有Https免验证,不建议使用 * * @throws KeyManagementException * @throws NoSuchAlgorithmException * @throws IOException */ public void initSSLALL() throws KeyManagementException, NoSuchAlgorithmException, IOException { URL url = new URL("https://trade3.guosen.com.cn/mtrade/check_version"); SSLContext context = SSLContext.getInstance("TLS"); context.init(null, new TrustManager[] {new TrustAllManager()}, null); HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory()); HttpsURLConnection.setDefaultHostnameVerifier( new HostnameVerifier() { @Override public boolean verify(String arg0, SSLSession arg1) { return true; } }); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(false); connection.setRequestMethod("GET"); connection.connect(); InputStream in = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line = ""; StringBuffer result = new StringBuffer(); while ((line = reader.readLine()) != null) { result.append(line); } String reString = result.toString(); Log.i("TTTT", reString); }
private static SSLContext createBougusServerSslContext() throws GeneralSecurityException, IOException { // Create keystore KeyStore ks = KeyStore.getInstance("JKS"); InputStream in = null; try { in = BogusSslContextFactory.class.getResourceAsStream(BOGUS_KEYSTORE); ks.load(in, BOGUS_PW); } finally { if (in != null) { try { in.close(); } catch (IOException ignored) { } } } // Set up key manager factory to use our key store KeyManagerFactory kmf = KeyManagerFactory.getInstance(KEY_MANAGER_FACTORY_ALGORITHM); kmf.init(ks, BOGUS_PW); // Initialize the SSLContext to work with our key managers. SSLContext sslContext = SSLContext.getInstance(PROTOCOL); sslContext.init(kmf.getKeyManagers(), BogusTrustManagerFactory.X509_MANAGERS, null); return sslContext; }
public static void trustAllHttpsURLConnection() { // Create a trust manager that does not validate certificate chains if (sslSocketFactory == null) { TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(X509Certificate[] certs, String authType) {} @Override public void checkServerTrusted(X509Certificate[] certs, String authType) {} } }; try { SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, trustAllCerts, null); sslSocketFactory = sslContext.getSocketFactory(); } catch (Throwable e) { Log.e("trustAllHttpsURLConnection", e.getMessage(), e); } } if (sslSocketFactory != null) { HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory); HttpsURLConnection.setDefaultHostnameVerifier( org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); } }
public static void main(String[] args) throws Exception { SSLContext sslContext = createSSLContext(); SSLServerSocketFactory fact = sslContext.getServerSocketFactory(); SSLServerSocket sSock = (SSLServerSocket) fact.createServerSocket(Utils.PORT_NO); // client authenticate where possible sSock.setWantClientAuth(true); for (; ; ) { SSLSocket sslSock = (SSLSocket) sSock.accept(); try { sslSock.startHandshake(); } catch (IOException e) { continue; } readRequest(sslSock.getInputStream()); SSLSession session = sslSock.getSession(); try { Principal clientID = session.getPeerPrincipal(); System.out.println("client identified as: " + clientID); } catch (SSLPeerUnverifiedException e) { System.out.println("client not authenticated"); } sendResponse(sslSock.getOutputStream()); sslSock.close(); } }
@Override public InputStream sendXmlRpc(byte[] request) throws IOException { // Create a trust manager that does not validate certificate for this connection TrustManager[] trustAllCerts = new TrustManager[] {new PyPITrustManager()}; try { SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, trustAllCerts, new SecureRandom()); final HttpConfigurable settings = HttpConfigurable.getInstance(); con = settings.openConnection(PYPI_LIST_URL); if (con instanceof HttpsURLConnection) { ((HttpsURLConnection) con).setSSLSocketFactory(sslContext.getSocketFactory()); } con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); con.setAllowUserInteraction(false); con.setRequestProperty("Content-Length", Integer.toString(request.length)); con.setRequestProperty("Content-Type", "text/xml"); if (auth != null) { con.setRequestProperty("Authorization", "Basic " + auth); } OutputStream out = con.getOutputStream(); out.write(request); out.flush(); out.close(); return con.getInputStream(); } catch (NoSuchAlgorithmException e) { LOG.warn(e.getMessage()); } catch (KeyManagementException e) { LOG.warn(e.getMessage()); } return super.sendXmlRpc(request); }
@SuppressLint("TrulyRandom") private XMPPConnection createConnection() { ConnectionConfiguration config = new ConnectionConfiguration(PreferenceUtils.getServerHost(context), PORT); SSLContext sc = null; MemorizingTrustManager mtm = null; try { mtm = new MemorizingTrustManager(context); sc = SSLContext.getInstance("TLS"); sc.init(null, new X509TrustManager[] {mtm}, new SecureRandom()); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); } catch (KeyManagementException e) { throw new IllegalStateException(e); } config.setCustomSSLContext(sc); config.setHostnameVerifier( mtm.wrapHostnameVerifier(new org.apache.http.conn.ssl.StrictHostnameVerifier())); config.setSecurityMode(SecurityMode.required); config.setReconnectionAllowed(false); config.setSendPresence(false); return new XMPPTCPConnection(config); }
public CertificateInstaller(Resource source, String host, int port, char[] passphrase) throws IOException, KeyStoreException, GeneralSecurityException { this.source = source; this.host = host; this.port = port; this.passphrase = passphrase; ks = null; InputStream in = source.getInputStream(); try { ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(in, passphrase); } finally { IOUtil.closeEL(in); } context = SSLContext.getInstance("TLS"); tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0]; tm = new SavingTrustManager(defaultTrustManager); context.init(null, new TrustManager[] {tm}, null); checkCertificate(); if (tm.chain == null) throw new IOException("Could not obtain server certificate chain"); }
public static CloseableHttpClient buildHttpClient() throws Exception { TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws CertificateException {} @Override public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws CertificateException {} } }; SSLContext sslcontext = SSLContext.getInstance("SSL"); sslcontext.init(null, trustAllCerts, new java.security.SecureRandom()); // Allow TLSv1 protocol only SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( sslcontext, new String[] {"TLSv1"}, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier()); CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); return httpclient; }