List of usage examples for javax.net.ssl SSLContext init
public final void init(KeyManager[] km, TrustManager[] tm, SecureRandom random) throws KeyManagementException
From source file:com.dbay.apns4j.tools.ApnsTools.java
public final static SocketFactory createSocketFactory(InputStream keyStore, String password, String keystoreType, String algorithm, String protocol) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException, KeyManagementException, CertificateExpiredException { char[] pwdChars = password.toCharArray(); KeyStore ks = KeyStore.getInstance(keystoreType); ks.load(keyStore, pwdChars);/*from w w w . ja v a 2 s . c o m*/ // ?? Enumeration<String> enums = ks.aliases(); String alias = ""; if (enums.hasMoreElements()) { alias = enums.nextElement(); } if (StringUtils.isNotEmpty(alias)) { X509Certificate certificate = (X509Certificate) ks.getCertificate(alias); if (null != certificate) { String type = certificate.getType(); int ver = certificate.getVersion(); String name = certificate.getSubjectDN().getName(); String serialNumber = certificate.getSerialNumber().toString(16); String issuerDN = certificate.getIssuerDN().getName(); String sigAlgName = certificate.getSigAlgName(); String publicAlgorithm = certificate.getPublicKey().getAlgorithm(); Date before = certificate.getNotBefore(); Date after = certificate.getNotAfter(); String beforeStr = DateFormatUtils.format(before, "yyyy-MM-dd HH:mm:ss"); String afterStr = DateFormatUtils.format(after, "yyyy-MM-dd HH:mm:ss"); // ?? long expire = DateUtil.getNumberOfDaysBetween(new Date(), after); if (expire <= 0) { if (LOG.isErrorEnabled()) { LOG.error( "?[{}], [{}], ?[{}], ??[{}], ?[{}], ??[{}], [{}], [{}][{}], ?[{}]", name, type, ver, serialNumber, issuerDN, sigAlgName, publicAlgorithm, beforeStr, afterStr, Math.abs(expire)); } throw new CertificateExpiredException("??[" + Math.abs(expire) + "]"); } if (LOG.isInfoEnabled()) { LOG.info( "?[{}], [{}], ?[{}], ??[{}], ?[{}], ??[{}], [{}], [{}][{}], ?[{}]?", name, type, ver, serialNumber, issuerDN, sigAlgName, publicAlgorithm, beforeStr, afterStr, expire); } } } KeyManagerFactory kf = KeyManagerFactory.getInstance(algorithm); kf.init(ks, pwdChars); TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm); tmf.init((KeyStore) null); SSLContext context = SSLContext.getInstance(protocol); context.init(kf.getKeyManagers(), tmf.getTrustManagers(), null); return context.getSocketFactory(); }
From source file:com.vtc.basetube.services.volley.ssl.EasySSLSocketFactory.java
private static SSLContext createEasySSLContext(Context context) throws IOException { try {// w w w .j a v a2s .co m // Client should authenticate itself with the valid certificate to // Server. InputStream clientStream = context.getResources().openRawResource(CERTIFICATE_RESOURCE_CLIENT); char[] password = "XXXXXXXXXXXXX".toCharArray(); KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load(clientStream, password); KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keyStore, password); // Client should also add the CA certificate obtained from server // and create TrustManager from it for the client to validate the // identity of the server. KeyStore trustStore = KeyStore.getInstance("BKS"); InputStream instream = null; instream = context.getResources().openRawResource(CERTIFICATE_RESOURCE_CA); try { trustStore.load(instream, "XXXXXXXX".toCharArray()); } catch (Exception e) { e.printStackTrace(); } finally { try { instream.close(); } catch (Exception ignore) { } } String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(trustStore); // Create an SSLContext that uses our TrustManager & Keystore SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyManagerFactory.getKeyManagers(), tmf.getTrustManagers(), null); return sslContext; } catch (Exception e) { e.printStackTrace(); throw new IOException(e.getMessage()); } }
From source file:org.reficio.ws.client.ssl.SSLUtils.java
public static SSLSocketFactory getMergedSocketFactory(org.reficio.ws.client.core.Security securityOne, Security securityTwo) throws GeneralSecurityException { X509KeyManager keyManagerOne = getKeyManager(securityOne.getKeyStore(), securityOne.getKeyStorePassword()); X509KeyManager keyManagerTwo = getKeyManager(securityTwo.getKeyStore(), securityTwo.getKeyStorePassword()); X509TrustManager trustManager = getMultiTrustManager(getTrustManager(securityOne.getTrustStore()), getTrustManager(securityTwo.getTrustStore())); SSLContext context = SSLContext.getInstance(securityOne.getSslContextProtocol()); boolean strictHostVerification = securityOne.isStrictHostVerification() && securityTwo.isStrictHostVerification(); context.init(new KeyManager[] { keyManagerOne, keyManagerTwo }, new TrustManager[] { trustManager }, new SecureRandom()); X509HostnameVerifier verifier = strictHostVerification ? SSLSocketFactory.STRICT_HOSTNAME_VERIFIER : SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; return new SSLSocketFactory(context, verifier); }
From source file:de.pniehus.odal.App.java
/** * This method initializes a Trustmanager that accepts self signed ssl * certificates/*from w ww . ja v a 2s.co m*/ * * This code of this method has been taken from * * @see <a href="https://stackoverflow.com/a/4453908">this Stackoverflow * post</a> and is licensed under the MIT License * * Copyright (c) 2010 nogudnik * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation files * (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ public static void untrustedSSLSetup() { 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) { } } }; try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (Exception e) { mainLogger.severe("Unable to setup support for unverified SSL certificates: " + e.getMessage()); } }
From source file:io.hops.security.HopsUtil.java
/** * Set the default HTTPS trust policy to trust anything. * * NOTE: Use it only during development or use it wisely! *///from w w w . jav a2 s . c om public static void trustAllHTTPS() { try { final SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); sslContext.init(null, trustAll, null); HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory()); HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String s, SSLSession sslSession) { return true; } }); } catch (GeneralSecurityException ex) { throw new IllegalStateException("Could not initialize SSLContext for CRL fetcher", ex); } }
From source file:com.vmware.identity.openidconnect.client.TestUtils.java
static IdmClient createIdmClient(AccessToken accessToken, String domainControllerFQDN, int domainControllerPort, KeyStore keyStore) throws Exception { TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keyStore);//from w ww . java 2 s .co m SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustManagerFactory.getTrustManagers(), null); IdmClient idmClient = new IdmClient(domainControllerFQDN, domainControllerPort, new DefaultHostnameVerifier(), sslContext); com.vmware.identity.rest.core.client.AccessToken restAccessToken = new com.vmware.identity.rest.core.client.AccessToken( accessToken.getValue(), com.vmware.identity.rest.core.client.AccessToken.Type.JWT); idmClient.setToken(restAccessToken); return idmClient; }
From source file:com.vmware.identity.openidconnect.client.TestUtils.java
static VmdirClient createVMdirClient(AccessToken accessToken, String domainControllerFQDN, int domainControllerPort, KeyStore keyStore) throws Exception { TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keyStore);//from www. j a v a 2 s . c o m SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustManagerFactory.getTrustManagers(), null); VmdirClient vmdirClient = new VmdirClient(domainControllerFQDN, domainControllerPort, new DefaultHostnameVerifier(), sslContext); com.vmware.identity.rest.core.client.AccessToken restAccessToken = new com.vmware.identity.rest.core.client.AccessToken( accessToken.getValue(), com.vmware.identity.rest.core.client.AccessToken.Type.JWT); vmdirClient.setToken(restAccessToken); return vmdirClient; }
From source file:com.camel.trainreserve.JDKHttpsClient.java
public static String doGet(String url) { InputStream in = null;/*from w w w . j a v a2s.c om*/ BufferedReader br = null; StringBuffer str_return = new StringBuffer(); try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, new TrustManager[] { new DefaultTrustManager() }, new java.security.SecureRandom()); URL console = new URL(url); HttpsURLConnection conn = (HttpsURLConnection) console.openConnection(); conn.setSSLSocketFactory(sc.getSocketFactory()); conn.setHostnameVerifier(new TrustAnyHostnameVerifier()); conn.connect(); in = conn.getInputStream(); br = new BufferedReader(new InputStreamReader(in)); String line = null; while ((line = br.readLine()) != null) { str_return = str_return.append(line); } conn.disconnect(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (KeyManagementException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { br.close(); in.close(); } catch (Exception e) { } } return str_return.toString(); }
From source file:app.android.auto.net.sampleapp.oauth.blackwork.EasyHttpClient.java
private static SSLContext createEasySSLContext() throws IOException { try {//from ww w . j a va 2 s .c o m SSLContext context = SSLContext.getInstance("TLS"); context.init(null, new TrustManager[] { new TrivialTrustManager() }, null); return context; } catch (Exception e) { throw new IOException(e.getMessage()); } }
From source file:com.camel.trainreserve.JDKHttpsClient.java
public static ByteArrayOutputStream doGetImg(String url, String cookieStr) { InputStream in = null;// w w w . ja v a2 s .c o m ByteArrayOutputStream outStream = null; try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, new TrustManager[] { new DefaultTrustManager() }, new SecureRandom()); URL console = new URL(url); HttpsURLConnection conn = (HttpsURLConnection) console.openConnection(); conn.setRequestProperty("Cookie", cookieStr); conn.setSSLSocketFactory(sc.getSocketFactory()); conn.setHostnameVerifier(new TrustAnyHostnameVerifier()); conn.connect(); in = conn.getInputStream(); outStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = in.read(buffer)) != -1) { outStream.write(buffer, 0, len); } conn.disconnect(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (KeyManagementException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { in.close(); } catch (Exception e) { } } return outStream; }