public static PoolingHttpClientConnectionManager getConnctionManager(){ Registry<ConnectionSocketFactory> socketFactoryRegistry = null; try { SSLConnectionSocketFactory trustSelfSignedSocketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(), new TrustAllHostNameVerifier()); socketFactoryRegistry = RegistryBuilder .<ConnectionSocketFactory> create() .register("http", new PlainConnectionSocketFactory()) .register("https", trustSelfSignedSocketFactory) .build(); } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) { Data.logger.warn("", e); } PoolingHttpClientConnectionManager cm = (socketFactoryRegistry != null) ? new PoolingHttpClientConnectionManager(socketFactoryRegistry): new PoolingHttpClientConnectionManager(); // twitter specific options cm.setMaxTotal(2000); cm.setDefaultMaxPerRoute(200); return cm; }
public SocketFactory createSocketFactory() { try { SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, new TrustManager[] { this }, null); return sslContext.getSocketFactory(); } catch (NoSuchAlgorithmException | KeyManagementException e) { throw new RuntimeException("Failed to create a SSL socket factory"); } }
@Bean public RestTemplate restTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException { SSLContext sslContext = SSLContexts.custom() .loadTrustMaterial(null, new TrustSelfSignedStrategy()) .build(); SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE); CloseableHttpClient httpClient = HttpClients.custom() .setSSLSocketFactory(sslConnectionSocketFactory) .build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); requestFactory.setHttpClient(httpClient); return new RestTemplate(requestFactory); }
/** * Prepare. * * @param requestURL the request URL * @return the URL processor * @throws IOException Signals that an I/O exception has occurred. * @throws KeyStoreException * @throws CertificateException * @throws NoSuchAlgorithmException * @throws KeyManagementException */ public URLProcessor prepare(URL requestURL) throws IOException, KeyManagementException, NoSuchAlgorithmException, CertificateException, KeyStoreException { // System.out.println("requestURL="); // System.out.println(requestURL); connection = (HttpsURLConnection) requestURL.openConnection(); connection.setInstanceFollowRedirects(false); Trust.trustSpecific(connection, truststoreFile); connection.setRequestMethod("GET"); if (accessToken != null) { connection.setRequestProperty("Authorization", "Bearer " + accessToken); } if (uploadFile != null) { injectUpload(); } return this; }
/** * Creates a SSLContext instance using the given information. * * @param keystore the full path to the keystore * @param keystorePasswd the keystore password * @param keystoreType the type of keystore (e.g., PKCS12, JKS) * @param protocol the protocol to use for the SSL connection * * @return a SSLContext instance * @throws KeyStoreException if any issues accessing the keystore * @throws IOException for any problems loading the keystores * @throws NoSuchAlgorithmException if an algorithm is found to be used but is unknown * @throws CertificateException if there is an issue with the certificate * @throws UnrecoverableKeyException if the key is insufficient * @throws KeyManagementException if unable to manage the key */ public static SSLContext createSslContext( final String keystore, final char[] keystorePasswd, final char[] keyPasswd, final String keystoreType, final String protocol) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException, KeyManagementException { // prepare the keystore final KeyStore keyStore = KeyStoreUtils.getKeyStore(keystoreType); try (final InputStream keyStoreStream = new FileInputStream(keystore)) { keyStore.load(keyStoreStream, keystorePasswd); } final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); if (keyPasswd == null) { keyManagerFactory.init(keyStore, keystorePasswd); } else { keyManagerFactory.init(keyStore, keyPasswd); } // initialize the ssl context final SSLContext ctx = SSLContext.getInstance(protocol); ctx.init(keyManagerFactory.getKeyManagers(), new TrustManager[0], new SecureRandom()); return ctx; }
public QMailHttpClient getHttpClient() throws MessagingException { if (httpClient == null) { httpClient = httpClientFactory.create(); // Disable automatic redirects on the http client. httpClient.getParams().setBooleanParameter("http.protocol.handle-redirects", false); // Setup a cookie store for forms-based authentication. httpContext = new BasicHttpContext(); authCookies = new BasicCookieStore(); httpContext.setAttribute(ClientContext.COOKIE_STORE, authCookies); SchemeRegistry reg = httpClient.getConnectionManager().getSchemeRegistry(); try { Scheme s = new Scheme("https", new WebDavSocketFactory(hostname, 443), 443); reg.register(s); } catch (NoSuchAlgorithmException nsa) { Timber.e(nsa, "NoSuchAlgorithmException in getHttpClient"); throw new MessagingException("NoSuchAlgorithmException in getHttpClient: ", nsa); } catch (KeyManagementException kme) { Timber.e(kme, "KeyManagementException in getHttpClient"); throw new MessagingException("KeyManagementException in getHttpClient: ", kme); } } return httpClient; }
private void handleInteractions(Socket socket) throws IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException, KeyManagementException, UnexpectedCommandException { ImapInteraction interaction = interactions.pop(); if (interaction instanceof ExpectedCommand) { readExpectedCommand((ExpectedCommand) interaction); } else if (interaction instanceof CannedResponse) { writeCannedResponse((CannedResponse) interaction); } else if (interaction instanceof CloseConnection) { clientSocket.close(); } else if (interaction instanceof EnableCompression) { enableCompression(socket); } else if (interaction instanceof UpgradeToTls) { upgradeToTls(socket); } }
private void upgradeToTls(Socket socket) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException, KeyManagementException { KeyStore keyStore = keyStoreProvider.getKeyStore(); String defaultAlgorithm = KeyManagerFactory.getDefaultAlgorithm(); KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(defaultAlgorithm); keyManagerFactory.init(keyStore, keyStoreProvider.getPassword()); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyManagerFactory.getKeyManagers(), null, null); SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket( socket, socket.getInetAddress().getHostAddress(), socket.getPort(), true); sslSocket.setUseClientMode(false); sslSocket.startHandshake(); input = Okio.buffer(Okio.source(sslSocket.getInputStream())); output = Okio.buffer(Okio.sink(sslSocket.getOutputStream())); }
private OkHttpUtils(long connectTimeOut, long readTimeOut, long writeTimeOut, int retrys) { OkHttpClient.Builder builder = getBuilder(connectTimeOut, readTimeOut, writeTimeOut, retrys); this.connectTimeOut = connectTimeOut; this.readTimeOut = readTimeOut; this.writeTimeOut = writeTimeOut; this.retrys = retrys; okHttpClient = builder.build(); try { ssl(builder); okHttpsClient = builder.build(); } catch (NoSuchAlgorithmException | KeyManagementException e) { log.error(e.getMessage(), e); throw new RuntimeException(e.getMessage()); } }
/** * Retrieve provider metadata. * Provider configuration information * Obtaining the provider configuration information can be done either out-of-band or using the optional discovery process: * * @throws IOException Signals that an I/O exception has occurred. * @throws ParseException the parse exception * @throws KeyStoreException * @throws CertificateException * @throws NoSuchAlgorithmException * @throws KeyManagementException */ public void retrieveProviderMetadata() throws IOException, ParseException, KeyManagementException, NoSuchAlgorithmException, CertificateException, KeyStoreException { URL providerConfigurationURL = issuerURI.resolve(URLPATH_WELL_KNOWN_OPENID).toURL(); // System.out.println(providerConfigurationURL); URLConnection conn = providerConfigurationURL.openConnection(); if (trustStoreFile != null) { Trust.trustSpecific((HttpsURLConnection) conn, trustStoreFile); } InputStream stream = conn.getInputStream(); // Read all data from URL String providerInfo = null; try (java.util.Scanner s = new java.util.Scanner(stream)) { providerInfo = s.useDelimiter("\\A").hasNext() ? s.next() : ""; } setProviderMetadata(OIDCProviderMetadata.parse(providerInfo)); }
/** * 获取LayeredConnectionSocketFactory 使用ssl单向认证 * * @date 2015年7月17日 * @return */ private LayeredConnectionSocketFactory getSSLSocketFactory() { try { SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { // 信任所有 public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }).build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); return sslsf; } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) { logger.error(e.getMessage(), e); throw new RuntimeException(e.getMessage(), e); } }
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 | KeyManagementException | KeyStoreException e) { throw new AssertionError(e); } }
/** * Will create a certificate-ignoring {@link SSLContext}. Please use with utmost caution as it undermines security, * but may be useful in certain testing or development scenarios. * * @return The SSLContext */ public static SSLContext buildCertificateIgnoringSslContext() { try { return SSLContexts .custom() .loadTrustMaterial(new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { return true; } }) .build(); } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) { throw new IllegalStateException("Unexpected exception while building the certificate-ignoring SSLContext.", e); } }
/** * Initialize the factory with custom trustStore * @param trustStore KeyStore */ public static synchronized void initTrustedSSLSocketFactory(final KeyStore trustStore) { try { final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509"); trustManagerFactory.init(trustStore); context = SSLContext.getInstance("SSL"); context.init(null, trustManagerFactory.getTrustManagers(), SecureRandom.getInstance("SHA1PRNG")); } catch (NoSuchAlgorithmException nsae) { throw new AlfrescoRuntimeException("The SSL socket factory cannot be initialized.", nsae); } catch (KeyStoreException kse) { throw new AlfrescoRuntimeException("The SSL socket factory cannot be initialized.", kse); } catch (KeyManagementException kme) { throw new AlfrescoRuntimeException("The SSL socket factory cannot be initialized.", kme); } }
private void create(Path path) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException { TrustManager[] trustManagers; KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, null); installCertificates(path, keyStore); String defaultAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(defaultAlgorithm); trustManagerFactory.init(keyStore); trustManagers = trustManagerFactory.getTrustManagers(); sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, trustManagers, null); trustManager = (X509TrustManager) trustManagers[0]; X509Certificate[] acceptedIssuers = trustManager.getAcceptedIssuers(); for (X509Certificate acceptedIssuer : acceptedIssuers) { logger.info("installed cert details: subject={} issuer={}", acceptedIssuer.getSubjectX500Principal(), acceptedIssuer.getIssuerX500Principal()); } }
/** * The parameter passed is the user enforced protocol. Does not catch * NoSuchAlgorithmException, WrongProperty test will use it. */ public void test(String expectedContextProto, String[] expectedDefaultProtos) throws NoSuchAlgorithmException { SSLContext context = null; try { if (expectedContextProto != null) { context = SSLContext.getInstance(expectedContextProto); context.init(null, null, null); } else { context = SSLContext.getDefault(); } printContextDetails(context); } catch (KeyManagementException ex) { error(null, ex); } validateContext(expectedContextProto, expectedDefaultProtos, context); }
public static void allowAllSSL() { HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { public boolean verify(String arg0, SSLSession arg1) { return true; } }); SSLContext context = null; if (trustManagers == null) { trustManagers = new TrustManager[]{new HttpsTrustManager()}; } try { context = SSLContext.getInstance("TLS"); context.init(null, trustManagers, new SecureRandom()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyManagementException e2) { e2.printStackTrace(); } HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory()); }
public static String triggerHttpGetWithCustomSSL(String requestUrl) { String result = null; try { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy() { public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { return true; } }); @SuppressWarnings("deprecation") HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(), hostnameVerifier); CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); HttpGet httpGet = new HttpGet("https://" + requestUrl); CloseableHttpResponse response = httpclient.execute(httpGet); try { if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { HttpEntity entity = response.getEntity(); result = EntityUtils.toString(entity); log.debug("Received response: " + result); } else { log.error("Request not successful. StatusCode was " + response.getStatusLine().getStatusCode()); } } finally { response.close(); } } catch (IOException | KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) { log.error("Error executing the request.", e); } return result; }
/** * 鍙戦�丟et璇锋眰 * @param url * @return * @throws NoSuchProviderException * @throws NoSuchAlgorithmException * @throws IOException * @throws KeyManagementException */ public static String get(String url,Boolean https) throws NoSuchAlgorithmException, NoSuchProviderException, IOException, KeyManagementException { StringBuffer bufferRes = null; TrustManager[] tm = { new MyX509TrustManager() }; SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); sslContext.init(null, tm, new java.security.SecureRandom()); // 浠庝笂杩癝SLContext瀵硅薄涓緱鍒癝SLSocketFactory瀵硅薄 SSLSocketFactory ssf = sslContext.getSocketFactory(); URL urlGet = new URL(url); HttpsURLConnection http = (HttpsURLConnection) urlGet.openConnection(); // 杩炴帴瓒呮椂 http.setConnectTimeout(25000); // 璇诲彇瓒呮椂 --鏈嶅姟鍣ㄥ搷搴旀瘮杈冩參锛屽澶ф椂闂� http.setReadTimeout(25000); http.setRequestMethod("GET"); http.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); http.setSSLSocketFactory(ssf); http.setHostnameVerifier(new Verifier()); http.setDoOutput(true); http.setDoInput(true); http.connect(); InputStream in = http.getInputStream(); BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET)); String valueString = null; bufferRes = new StringBuffer(); while ((valueString = read.readLine()) != null){ bufferRes.append(valueString); } in.close(); if (http != null) { // 鍏抽棴杩炴帴 http.disconnect(); } return bufferRes.toString(); }
public Socket createSocket(Socket socket, String host, int port, String clientCertificateAlias) throws NoSuchAlgorithmException, KeyManagementException, MessagingException, IOException { TrustManager[] trustManagers = new TrustManager[] { TrustManagerFactory.get(host, port) }; KeyManager[] keyManagers = null; if (!TextUtils.isEmpty(clientCertificateAlias)) { keyManagers = new KeyManager[] { new KeyChainKeyManager(context, clientCertificateAlias) }; } SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyManagers, trustManagers, null); SSLSocketFactory socketFactory = sslContext.getSocketFactory(); Socket trustedSocket; if (socket == null) { trustedSocket = socketFactory.createSocket(); } else { trustedSocket = socketFactory.createSocket(socket, host, port, true); } SSLSocket sslSocket = (SSLSocket) trustedSocket; hardenSocket(sslSocket); setSniHost(socketFactory, sslSocket, host); return trustedSocket; }
/** * 鍙戦�丟et璇锋眰 * @param url * @return * @throws NoSuchProviderException * @throws NoSuchAlgorithmException * @throws IOException * @throws KeyManagementException */ public static String get(String url) throws NoSuchAlgorithmException, NoSuchProviderException, IOException, KeyManagementException { if(enableSSL){ return get(url,true); }else{ StringBuffer bufferRes = null; URL urlGet = new URL(url); HttpURLConnection http = (HttpURLConnection) urlGet.openConnection(); // 杩炴帴瓒呮椂 http.setConnectTimeout(25000); // 璇诲彇瓒呮椂 --鏈嶅姟鍣ㄥ搷搴旀瘮杈冩參锛屽澶ф椂闂� http.setReadTimeout(25000); http.setRequestMethod("GET"); http.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); http.setDoOutput(true); http.setDoInput(true); http.connect(); InputStream in = http.getInputStream(); BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET)); String valueString = null; bufferRes = new StringBuffer(); while ((valueString = read.readLine()) != null){ bufferRes.append(valueString); } in.close(); if (http != null) { // 鍏抽棴杩炴帴 http.disconnect(); } return bufferRes.toString(); } }
/** * Returns the VM's default SSL socket factory, using {@code trustManager} for trusted root * certificates. */ private SSLSocketFactory defaultSslSocketFactory(X509TrustManager trustManager) throws NoSuchAlgorithmException, KeyManagementException { SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, new TrustManager[] { trustManager }, null); return sslContext.getSocketFactory(); }
public SSLContext build() throws NoSuchAlgorithmException, KeyManagementException { final SSLContext sslcontext = SSLContext.getInstance( this.protocol != null ? this.protocol : TLS); sslcontext.init( !keymanagers.isEmpty() ? keymanagers.toArray(new KeyManager[keymanagers.size()]) : null, !trustmanagers.isEmpty() ? trustmanagers.toArray(new TrustManager[trustmanagers.size()]) : null, secureRandom); return sslcontext; }
@Test public void testCreateSSLContextKeyManagementException() { SSLOption option = SSLOption.build(DIR + "/server.ssl.properties"); SSLCustom custom = new SSLCustom() { @Override public String getFullPath(String filename) { return DIR + "/ssl/" + filename; } @Override public char[] decode(char[] encrypted) { return encrypted; } }; new MockUp<SSLContext>() { @Mock public final SSLContext getInstance(String type) throws KeyManagementException { throw new KeyManagementException(); } }; try { SSLContext context = SSLManager.createSSLContext(option, custom); Assert.assertNotNull(context); } catch (Exception e) { Assert.assertEquals("java.lang.IllegalArgumentException", e.getClass().getName()); } }
/** * 鍙戦�丳ost璇锋眰 * @param url * @param params * @return * @throws IOException * @throws NoSuchProviderException * @throws NoSuchAlgorithmException * @throws KeyManagementException */ public static String post(String url, String params,Boolean https) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException { StringBuffer bufferRes = null; TrustManager[] tm = { new MyX509TrustManager() }; SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); sslContext.init(null, tm, new java.security.SecureRandom()); // 浠庝笂杩癝SLContext瀵硅薄涓緱鍒癝SLSocketFactory瀵硅薄 SSLSocketFactory ssf = sslContext.getSocketFactory(); URL urlGet = new URL(url); HttpsURLConnection http = (HttpsURLConnection) urlGet.openConnection(); // 杩炴帴瓒呮椂 http.setConnectTimeout(50000); // 璇诲彇瓒呮椂 --鏈嶅姟鍣ㄥ搷搴旀瘮杈冩參锛屽澶ф椂闂� http.setReadTimeout(50000); http.setRequestMethod("POST"); http.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); http.setSSLSocketFactory(ssf); http.setHostnameVerifier(new Verifier()); http.setDoOutput(true); http.setDoInput(true); http.connect(); OutputStream out = http.getOutputStream(); out.write(params.getBytes("UTF-8")); out.flush(); out.close(); InputStream in = http.getInputStream(); BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET)); String valueString = null; bufferRes = new StringBuffer(); while ((valueString = read.readLine()) != null){ bufferRes.append(valueString); } in.close(); if (http != null) { // 鍏抽棴杩炴帴 http.disconnect(); } return bufferRes.toString(); }
/** * UserInfo Request * Using the access token, information about the end user can be obtained by making a user info request * * @throws KeyStoreException * @throws CertificateException * @throws NoSuchAlgorithmException * @throws KeyManagementException * @throws ParseException * @throws IOException * @throws FileNotFoundException */ public void requestUserInfo() throws KeyManagementException, NoSuchAlgorithmException, CertificateException, KeyStoreException, ParseException, FileNotFoundException, IOException { if (accessToken == null) { System.err.println(this.getClass().getSimpleName() + " - Access Token null, stopping UserInfo retrieval"); return; } UserInfoRequest userInfoReq = new UserInfoRequest( userInfoEndpointURI, (BearerAccessToken) accessToken); HTTPResponse userInfoHTTPResp = null; userInfoHTTPResp = userInfoReq.toHTTPRequest().send(null, Trust.getSocketFactory(trustStoreFile)); UserInfoResponse userInfoResponse = null; userInfoResponse = UserInfoResponse.parse(userInfoHTTPResp); if (userInfoResponse instanceof UserInfoErrorResponse) { UserInfoErrorResponse errorResponse = ((UserInfoErrorResponse) userInfoResponse); ErrorObject error = errorResponse.getErrorObject(); System.err.println(this.getClass().getSimpleName() + " - " + errorResponse.indicatesSuccess()); System.err.println("Userinfo retrieval failed:"); System.err.println(errorResponse); System.err.println(error); System.err.println(error.getHTTPStatusCode()); System.err.println(userInfoHTTPResp.getStatusCode()); System.err.println(userInfoHTTPResp.getContent()); System.err.println(userInfoHTTPResp.getWWWAuthenticate()); System.err.println(userInfoHTTPResp.getLocation()); } UserInfoSuccessResponse successResponse = (UserInfoSuccessResponse) userInfoResponse; userInfoClaims = successResponse.getUserInfo().toJSONObject(); }
/** * Gets a SSLContext to be trusted. * * @param trustStoreFile the trust store file * @return the trustable SSL context * @throws IOException * @throws FileNotFoundException * @throws CertificateException * @throws NoSuchAlgorithmException * @throws KeyStoreException * @throws KeyManagementException */ private static SSLContext getTrustableSSLContext(File trustStoreFile) throws NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException, KeyStoreException, KeyManagementException { SSLContext sslContext = null; KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(new FileInputStream(trustStoreFile), TRUSTSTORE_PASSWORD.toCharArray()); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(trustStore); TrustManager[] tms = tmf.getTrustManagers(); sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, tms, null); return sslContext; }
/** * Opens the OpenID Connect dialog */ public static void showAuthenticationDialog() { try { OIDCAuthorization.getInstance().setIssuerURI(Application.getGlobalInfo().getOIDCIssuerURI()); OIDCAuthorization.getInstance().setTranslator(Language.getInstance()); OIDCAuthorization.getInstance().setTrustStore(new File(Application.getGlobalInfo().getPathProperty(true) + Trust.OIDC_TRUST_STORE)); OIDCAuthorization.getInstance().setAvailabilityHandler( new OIDCResourceAvailabilityHandler() { /* (non-Javadoc) * @see de.enflexit.oidc.OIDCResourceAvailabilityHandler#onResourceAvailable(de.enflexit.oidc.OIDCAuthorization.URLProcessor) */ @Override public void onResourceAvailable(URLProcessor urlProcessor) { Application.getGlobalInfo().setOIDCUsername(OIDCAuthorization.getInstance().getLastSuccessfulUser()); } /* (non-Javadoc) * @see de.enflexit.oidc.OIDCResourceAvailabilityHandler#onAuthorizationNecessary(de.enflexit.oidc.OIDCAuthorization) */ @Override public boolean onAuthorizationNecessary(OIDCAuthorization oidcAuthorization) { return true; // show the login panel } }); OIDCAuthorization.getInstance().accessResource(OIDCPanel.DEBUG_RESOURCE_URI, getGlobalInfo().getOIDCUsername(), getMainWindow()); } catch (URISyntaxException | KeyManagementException | NoSuchAlgorithmException | CertificateException | KeyStoreException | IOException ex) { //ex.printStackTrace(); System.err.println("Authentication failed: "+ex.getClass()+": "+ex.getMessage()); } }
protected void initSSLContext( final SSLContext sslcontext, final Collection<KeyManager> keyManagers, final Collection<TrustManager> trustManagers, final SecureRandom secureRandom) throws KeyManagementException { sslcontext.init( !keyManagers.isEmpty() ? keyManagers.toArray(new KeyManager[keyManagers.size()]) : null, !trustManagers.isEmpty() ? trustManagers.toArray(new TrustManager[trustManagers.size()]) : null, secureRandom); }
/** * 鍙戦�丳ost璇锋眰 * @param url 璇锋眰鍦板潃 * @param params 璇锋眰鍙傛暟 * @param https 鏄惁鍚姩https * @return * @throws IOException * @throws NoSuchProviderException * @throws NoSuchAlgorithmException * @throws KeyManagementException */ public static String post(String url, String params) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException { if(enableSSL){ return post(url,params,true); }else{ StringBuffer bufferRes = null; URL urlGet = new URL(url); HttpURLConnection http = (HttpURLConnection) urlGet.openConnection(); // 杩炴帴瓒呮椂 http.setConnectTimeout(50000); // 璇诲彇瓒呮椂 --鏈嶅姟鍣ㄥ搷搴旀瘮杈冩參锛屽澶ф椂闂� http.setReadTimeout(50000); http.setRequestMethod("POST"); http.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); http.setDoOutput(true); http.setDoInput(true); http.connect(); OutputStream out = http.getOutputStream(); out.write(params.getBytes("UTF-8")); out.flush(); out.close(); InputStream in = http.getInputStream(); BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET)); String valueString = null; bufferRes = new StringBuffer(); while ((valueString = read.readLine()) != null){ bufferRes.append(valueString); } in.close(); if (http != null) { // 鍏抽棴杩炴帴 http.disconnect(); } return bufferRes.toString(); } }
private synchronized void initSSL(ChannelPipeline p) throws X509Exception, KeyManagementException, NoSuchAlgorithmException { String authProviderProp = System.getProperty(ZKConfig.SSL_AUTHPROVIDER); SSLContext sslContext; if (authProviderProp == null) { sslContext = X509Util.createSSLContext(); } else { sslContext = SSLContext.getInstance("TLSv1"); X509AuthenticationProvider authProvider = (X509AuthenticationProvider)ProviderRegistry.getProvider( System.getProperty(ZKConfig.SSL_AUTHPROVIDER, "x509")); if (authProvider == null) { LOG.error("Auth provider not found: {}", authProviderProp); throw new SSLContextException( "Could not create SSLContext with specified auth provider: " + authProviderProp); } sslContext.init(new X509KeyManager[] { authProvider.getKeyManager() }, new X509TrustManager[] { authProvider.getTrustManager() }, null); } SSLEngine sslEngine = sslContext.createSSLEngine(); sslEngine.setUseClientMode(false); sslEngine.setNeedClientAuth(true); p.addLast("ssl", new SslHandler(sslEngine)); LOG.info("SSL handler added for channel: {}", p.getChannel()); }
protected RestClient buildClient(Settings settings, HttpHost[] hosts) throws IOException { RestClientBuilder builder = RestClient.builder(hosts); String keystorePath = settings.get(TRUSTSTORE_PATH); if (keystorePath != null) { final String keystorePass = settings.get(TRUSTSTORE_PASSWORD); if (keystorePass == null) { throw new IllegalStateException(TRUSTSTORE_PATH + " is provided but not " + TRUSTSTORE_PASSWORD); } Path path = PathUtils.get(keystorePath); if (!Files.exists(path)) { throw new IllegalStateException(TRUSTSTORE_PATH + " is set but points to a non-existing file"); } try { KeyStore keyStore = KeyStore.getInstance("jks"); try (InputStream is = Files.newInputStream(path)) { keyStore.load(is, keystorePass.toCharArray()); } SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(keyStore, null).build(); SSLIOSessionStrategy sessionStrategy = new SSLIOSessionStrategy(sslcontext); builder.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLStrategy(sessionStrategy)); } catch (KeyStoreException|NoSuchAlgorithmException|KeyManagementException|CertificateException e) { throw new RuntimeException("Error setting up ssl", e); } } try (ThreadContext threadContext = new ThreadContext(settings)) { Header[] defaultHeaders = new Header[threadContext.getHeaders().size()]; int i = 0; for (Map.Entry<String, String> entry : threadContext.getHeaders().entrySet()) { defaultHeaders[i++] = new BasicHeader(entry.getKey(), entry.getValue()); } builder.setDefaultHeaders(defaultHeaders); } return builder.build(); }
private SSLSocketFactory getSSLSocketFactory() { try { return new TLSSocketFactory(); } catch (NoSuchAlgorithmException | KeyManagementException e) { LOG.error("Error while creating SSL socket factory!", e); return null; } }
public static HttpFetcher getDefault() { HttpFetcher fetcher = new HttpFetcher(); try { fetcher.init(); } catch (KeyManagementException | NoSuchAlgorithmException e) { e.printStackTrace(); } return fetcher; }
public HttpFetcher build() { try { fetcher.init(); } catch (KeyManagementException | NoSuchAlgorithmException e) { e.printStackTrace(); } return fetcher; }