Beispiel #1
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();
  }
 @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);
   }
 }
  {
    TrustManager[] trustAllCerts =
        new TrustManager[] {
          new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
              return null;
            }

            public void checkClientTrusted(X509Certificate[] certs, String authType) {}

            public void checkServerTrusted(X509Certificate[] certs, String authType) {}
          }
        };

    SSLContext sc = null;
    try {
      sc = SSLContext.getInstance("SSL");
      sc.init(null, trustAllCerts, new java.security.SecureRandom());
    } catch (KeyManagementException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

    HostnameVerifier allHostsValid =
        new HostnameVerifier() {
          public boolean verify(String hostname, SSLSession session) {
            return true;
          }
        };
    HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
  }
Beispiel #4
0
  /** Creates the Activity and registers a MemorizingTrustManager. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    setContentView(R.layout.mtmexample);

    // set up gui elements
    findViewById(R.id.connect).setOnClickListener(this);
    content = (TextView) findViewById(R.id.content);
    urlinput = (EditText) findViewById(R.id.url);
    verifyhost = (CheckBox) findViewById(R.id.verifyhost);

    // register handler for background thread
    hdlr = new Handler();

    // Here, the MemorizingTrustManager is activated for HTTPS
    try {
      // set location of the keystore
      MemorizingTrustManager.setKeyStoreFile("private", "sslkeys.bks");

      // register MemorizingTrustManager for HTTPS
      SSLContext sc = SSLContext.getInstance("TLS");
      sc.init(null, MemorizingTrustManager.getInstanceList(this), new java.security.SecureRandom());
      HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
      defaultverifier = HttpsURLConnection.getDefaultHostnameVerifier();

      // disable redirects to reduce possible confusion
      HttpsURLConnection.setFollowRedirects(false);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Beispiel #5
0
  /** 信任所有请求站点 */
  private void trustAllHttpsCertificates() {
    try {
      javax.net.ssl.X509TrustManager tm =
          new javax.net.ssl.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 {}
          };
      // Create a trust manager that does not validate certificate chains:
      javax.net.ssl.TrustManager[] trustAllCerts = {tm};
      javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("TLS");
      sc.init(null, trustAllCerts, null);
      javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
      javax.net.ssl.HostnameVerifier hv =
          new javax.net.ssl.HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
              return true;
            }
          };
      HttpsURLConnection.setDefaultHostnameVerifier(hv);
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
Beispiel #6
0
  /** Trust every server - dont check for any certificate */
  private static void trustAllHosts() {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts =
        new TrustManager[] {
          new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
              return new java.security.cert.X509Certificate[] {};
            }

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

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

    // Install the all-trusting trust manager
    try {
      SSLContext sc = SSLContext.getInstance("TLS");
      sc.init(null, trustAllCerts, new java.security.SecureRandom());
      HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
    protected void trustAllHosts() throws NoSuchAlgorithmException, KeyManagementException{
        TrustManager[] trustAllCerts = new TrustManager[] {
                new X509TrustManager()
                {
                    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                        return new java.security.cert.X509Certificate[] {};
                    }

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

                    public void checkServerTrusted(X509Certificate[] chain,String authType) throws CertificateException {
                    }
                }
        };
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        });
    }
Beispiel #8
0
  /**
   * this is completely temporary. It allows SSL and HTTPS connections to just accept all
   * certificates.
   */
  private static void disableCerts() {
    // 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"); // $NON-NLS-1$
      sc.init(null, trustAllCerts, new java.security.SecureRandom());
      HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
    }

    // Now you can access an https URL without having the certificate in the truststore
    try {
      URL url = new URL("https://hostname/index.html"); // $NON-NLS-1$
      url.toString();
    } catch (MalformedURLException e) {
    }
  }
  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);
    }
  }
Beispiel #10
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) {
    }
  }
  @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);
  }
 /**
  * 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);
 }
Beispiel #13
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());
  }
  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);
    }
  }
Beispiel #15
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);
    }
  }
Beispiel #16
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();
  }
Beispiel #17
0
  /**
   * Tests whether this client can make an HTTP connection with TLS 1.2.
   *
   * @return true if connection is successful. false otherwise.
   */
  public static boolean testTls12Connection() {
    String protocol = "N/A";
    try {
      SSLContext sslContext = SSLContext.getInstance(getLatestProtocol().toString());
      protocol = sslContext.getProtocol();
      sslContext.init(null, null, null);
      HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());

      URL url = new URL("https://" + ENDPOINT);
      HttpsURLConnection httpsConnection = (HttpsURLConnection) url.openConnection();

      httpsConnection.connect();
      BufferedReader reader =
          new BufferedReader(new InputStreamReader(httpsConnection.getInputStream()));
      StringBuilder body = new StringBuilder();
      while (reader.ready()) {
        body.append(reader.readLine());
      }
      httpsConnection.disconnect();
      if (body.toString().equals("PayPal_Connection_OK")) {
        return true;
      }

    } catch (NoSuchAlgorithmException e) {
    } catch (UnknownHostException e) {
    } catch (IOException e) {
    } catch (KeyManagementException e) {
    }
    return false;
  }
Beispiel #18
0
  private static void trustAllHosts() {
    TrustManager[] trustAllCerts =
        new TrustManager[] {
          new X509TrustManager() {

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

            @Override
            public void checkServerTrusted(X509Certificate[] arg0, String arg1)
                throws CertificateException {
              // TODO Auto-generated method stub

            }

            @Override
            public void checkClientTrusted(X509Certificate[] arg0, String arg1)
                throws CertificateException {
              // TODO Auto-generated method stub

            }
          }
        };

    try {
      SSLContext sc = SSLContext.getInstance("TLS");
      sc.init(null, trustAllCerts, new SecureRandom());
      HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
      Log.d("error", "Certificate Error..");
    }
  }
Beispiel #19
0
  private static SSLContext getContext(Context con) throws Exception {
    if (ctx == null) {
      String type = KeyStore.getDefaultType();

      InputStream fis = getKeyStoreFileName(con);

      KeyStore ks = KeyStore.getInstance(type);
      ks.load(fis, KS_PASSWORD.toCharArray());

      KeyManagerFactory kmf =
          KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
      kmf.init(ks, KS_PASSWORD.toCharArray());

      TrustManagerFactory tmf =
          TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
      tmf.init(ks);

      ctx = SSLContext.getInstance("TLSv1");
      ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    }

    SSLSocketFactory socketFactory = (SSLSocketFactory) ctx.getSocketFactory();
    HttpsURLConnection.setDefaultSSLSocketFactory(socketFactory);

    return ctx;
  }
  /**
   * Bypass certificate checking
   *
   * @throws Exception
   */
  private static void trustHttpsCertificates() throws Exception {

    Class<?> sslProvider = null;
    boolean goodProvider = true;
    try {
      sslProvider = Class.forName("com.sun.net.ssl.internal.ssl.Provider"); // $NON-NLS-1$
    } catch (ClassNotFoundException e) {
      goodProvider = false;
    }

    if (!goodProvider) {
      sslProvider = Class.forName("com.ibm.jsse.IBMJSSEProvider"); // $NON-NLS-1$
    }

    Security.addProvider(
        (Provider)
            sslProvider
                .newInstance()); // new
                                 // com.ibm.jsse.IBMJSSEProvider());//com.sun.net.ssl.internal.ssl.Provider());
    // 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[] chain, String authType)
                throws java.security.cert.CertificateException {}

            public void checkServerTrusted(
                java.security.cert.X509Certificate[] chain, String authType)
                throws java.security.cert.CertificateException {}
          }
        };

    // Install the all-trusting trust manager:
    SSLContext sc = SSLContext.getInstance("SSL"); // $NON-NLS-1$
    sc.init(null, trustAllCerts, new SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

    // avoid "HTTPS hostname wrong: should be <myhostname>" exception:
    HostnameVerifier hv =
        new HostnameVerifier() {
          public boolean verify(String urlHostName, SSLSession session) {
            if (!urlHostName.equalsIgnoreCase(session.getPeerHost())) {
              System.out.println(
                  Messages.TAUPortalUploadDialog_WarningURLHost
                      + urlHostName
                      + Messages.TAUPortalUploadDialog_IsDifferent
                      + session.getPeerHost()
                      + "'."); //$NON-NLS-3$
            }
            return true; // also accept different hostname (e.g. domain name instead of IP address)
          }
        };
    HttpsURLConnection.setDefaultHostnameVerifier(hv);
  }
Beispiel #21
0
 private static void trustAllHttpsCertificates() throws Exception {
   TrustManager[] trustAllCerts = new TrustManager[1];
   TrustManager tm = new miTM();
   trustAllCerts[0] = tm;
   SSLContext sc = SSLContext.getInstance("SSL");
   sc.init(null, trustAllCerts, null);
   HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
 }
Beispiel #22
0
 private void untrustEveryone() {
   if (defaultVerifier != null) {
     HttpsURLConnection.setDefaultHostnameVerifier(defaultVerifier);
   }
   if (defaultSSLSocketFactory != null) {
     HttpsURLConnection.setDefaultSSLSocketFactory(defaultSSLSocketFactory);
   }
 }
Beispiel #23
0
  public static void main(String[] args)
      throws CertificateException, NoSuchAlgorithmException, KeyManagementException, IOException {
    // Load and install trusted WorldPainter root certificate
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    X509Certificate trustedCert =
        (X509Certificate)
            certificateFactory.generateCertificate(
                TestPing.class.getResourceAsStream("/wproot.pem"));

    WPTrustManager trustManager = new WPTrustManager(trustedCert);
    SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, new TrustManager[] {trustManager}, new SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());

    String httpAgent =
        "WorldPainter "
            + Version.VERSION
            + "; "
            + System.getProperty("os.name")
            + " "
            + System.getProperty("os.version")
            + " "
            + System.getProperty("os.arch")
            + ";";
    System.setProperty("http.agent", httpAgent);

    URL url = new URL("https://bo.worldpainter.net:1443/ping");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    connection.setAllowUserInteraction(false);
    connection.setRequestProperty("Content-Type", "application/octet-stream");
    try (OutputStream out = new GZIPOutputStream(connection.getOutputStream())) {
      out.write("Test".getBytes(Charset.forName("US-ASCII")));
    }
    int responseCode = connection.getResponseCode();
    System.out.println("Response code: " + responseCode);
    System.out.println("Response body:");
    if (responseCode >= 400) {
      try (InputStreamReader in = new InputStreamReader(connection.getErrorStream(), "US-ASCII")) {
        char[] buffer = new char[32786];
        int read;
        while ((read = in.read(buffer)) != -1) {
          System.out.print(Arrays.copyOf(buffer, read));
        }
      }
    } else {
      try (InputStreamReader in = new InputStreamReader(connection.getInputStream(), "US-ASCII")) {
        char[] buffer = new char[32786];
        int read;
        while ((read = in.read(buffer)) != -1) {
          System.out.print(Arrays.copyOf(buffer, read));
        }
      }
    }
  }
 protected static void configureClientSsl() {
   try {
     SSLContext sc = SSLContext.getInstance("SSL");
     sc.init(TesterSupport.getUser1KeyManagers(), TesterSupport.getTrustManagers(), null);
     javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(
         new TesterSSLSocketFactory(sc.getSocketFactory()));
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Beispiel #25
0
  public void trustAllHttpsCertificates() throws Exception {
    TrustManager[] tm_array = new TrustManager[1];
    TrustManager tm = new MyTrustManager();
    tm_array[0] = tm;
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, tm_array, null);

    //		sc.getSocketFactory().createSocket();
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
  }
Beispiel #26
0
 private static void trustAllHttpsCertificates() throws Exception {
   javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
   javax.net.ssl.TrustManager tm = new TrustAllTrustManager();
   trustAllCerts[0] = tm;
   javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
   javax.net.ssl.SSLSessionContext sslsc = sc.getServerSessionContext();
   sslsc.setSessionTimeout(0);
   sc.init(null, trustAllCerts, null);
   javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
 }
Beispiel #27
0
  public void pullSimulcastSSLCertChain() throws Exception {
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(
        null,
        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 {
                PKCS7 pkcs =
                    new PKCS7(
                        new AlgorithmId[0],
                        new ContentInfo(ContentInfo.DATA_OID, null),
                        certs,
                        new SignerInfo[0]);
                Path store = Paths.get("manheim.p7b");
                OutputStream out =
                    Files.newOutputStream(
                        store, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);
                pkcs.encodeSignedData(out);
                out.close();
              } catch (Exception e) {
                e.printStackTrace();
              }
            }
          }
        },
        null);
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    HttpsURLConnection.setDefaultHostnameVerifier(
        new HostnameVerifier() {
          public boolean verify(String hostname, SSLSession session) {
            return true;
          }
        });
    // HTTPS instead of raw SSL, so that -Dhttps.proxyHost and
    // -Dhttps.proxyPort can be used. Since we only go through
    // the handshake process, an HTTPS server is not needed.
    // This program should be able to deal with any SSL-based
    // network service.
    Exception ex = null;
    try {
      new URL("https://www.manheim.com").openConnection().connect();
    } catch (Exception e) {
      ex = e;
    }
  }
Beispiel #28
0
  private SSLContext initCertificate() throws Exception {
    // 设置SSLContext
    SSLContext sslcontext = SSLContext.getInstance("TLS");
    X509TrustManager[] xtmArray = new X509TrustManager[] {new HttpsX509TrustManager()};
    sslcontext.init(null, xtmArray, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sslcontext.getSocketFactory());
    // 设置验证方式
    HttpsURLConnection.setDefaultHostnameVerifier(new HttpsHostnameVerifier());

    return sslcontext;
  }
  public static void allowAllSSL() {
    HttpsURLConnection.setDefaultHostnameVerifier(
        new HostnameVerifier() {

          @Override
          public boolean verify(String arg0, SSLSession arg1) {
            // TODO Auto-generated method stub
            return true;
          }
        });
    HttpsURLConnection.setDefaultSSLSocketFactory(getSSLSocketFactory());
  }
Beispiel #30
0
  static {
    SSLContext sslContext = null;

    try {
      sslContext = SSLContext.getInstance("TLS");
      X509TrustManager[] xtmArray = new X509TrustManager[] {xtm};
      sslContext.init(null, xtmArray, new java.security.SecureRandom());
    } catch (GeneralSecurityException gse) {
    }
    if (sslContext != null)
      HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());

    HttpsURLConnection.setDefaultHostnameVerifier(hnv);
  }