Example #1
1
  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;
  }
Example #2
1
  /**
   * 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();
  }
  public void init() throws Exception, CertificateException, FileNotFoundException, IOException {
    if (sipStack.securityManagerProvider.getKeyManagers(false) == null
        || sipStack.securityManagerProvider.getTrustManagers(false) == null
        || sipStack.securityManagerProvider.getTrustManagers(true) == null) {
      if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
        logger.logDebug("TLS initialization failed due to NULL security config");
      }
      return; // The settings
    }

    sslServerCtx = SSLContext.getInstance("TLS");
    sslClientCtx = SSLContext.getInstance("TLS");

    if (sipStack.getClientAuth() == ClientAuthType.DisabledAll) {
      if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
        logger.logDebug(
            "ClientAuth " + sipStack.getClientAuth() + " bypassing all cert validations");
      }
      sslServerCtx.init(
          sipStack.securityManagerProvider.getKeyManagers(false), trustAllCerts, null);
      sslClientCtx.init(sipStack.securityManagerProvider.getKeyManagers(true), trustAllCerts, null);
    } else {
      if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
        logger.logDebug("ClientAuth " + sipStack.getClientAuth());
      }
      sslServerCtx.init(
          sipStack.securityManagerProvider.getKeyManagers(false),
          sipStack.securityManagerProvider.getTrustManagers(false),
          null);
      sslClientCtx.init(
          sipStack.securityManagerProvider.getKeyManagers(true),
          sipStack.securityManagerProvider.getTrustManagers(true),
          null);
    }
  }
  static {
    String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
    if (algorithm == null) {
      algorithm = "SunX509";
    }

    SSLContext serverContext;
    SSLContext clientContext;
    try {
      KeyStore ks = KeyStore.getInstance("JKS");
      ks.load(BogusKeyStore.asInputStream(), BogusKeyStore.getKeyStorePassword());

      // Set up key manager factory to use our key store
      KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
      kmf.init(ks, BogusKeyStore.getCertificatePassword());

      // Initialize the SSLContext to work with our key managers.
      serverContext = SSLContext.getInstance(PROTOCOL);
      serverContext.init(kmf.getKeyManagers(), null, null);
    } catch (Exception e) {
      throw new Error("Failed to initialize the server-side SSLContext", e);
    }

    try {
      clientContext = SSLContext.getInstance(PROTOCOL);
      clientContext.init(null, BogusTrustManagerFactory.getTrustManagers(), null);
    } catch (Exception e) {
      throw new Error("Failed to initialize the client-side SSLContext", e);
    }

    SERVER_CONTEXT = serverContext;
    CLIENT_CONTEXT = clientContext;
  }
Example #5
0
  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());
  }
Example #6
0
  @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());
  }
Example #7
0
  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();
  }
Example #8
0
 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);
   }
 }
  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;
  }
Example #10
0
  // =========================================================================================================
  // 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);
    }
  }
Example #11
0
  /** 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);
    }
  }
  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;
  }
  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();
    }
  }
Example #14
0
  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);
    }
  }
  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();
  }
Example #16
0
  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;
  }
Example #17
0
  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;
    }
  }
  @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);
  }
Example #19
0
  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");
  }
Example #20
0
  /**
   * 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);
    }
  }
  public CustomSSLSocketFactory(KeyStore truststore)
      throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException,
          UnrecoverableKeyException {

    super(truststore);

    TrustManager tm =
        new X509TrustManager() {

          @Override
          public void checkClientTrusted(X509Certificate[] chain, String authType)
              throws CertificateException {}

          @Override
          public void checkServerTrusted(X509Certificate[] chain, String authType)
              throws CertificateException {}

          @Override
          public X509Certificate[] getAcceptedIssuers() {
            return null;
          }
        };

    sslContext.init(null, new TrustManager[] {tm}, null);
  }
Example #22
0
  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 方式,支持指定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);
 }
Example #25
0
 @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 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;
  }
 /**
  * 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);
 }
Example #28
0
  @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);
  }
    @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);
    }
  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;
  }