Example #1
0
  private static SSLSocketFactory getSocketFactory(Boolean d) {
    // Enable debug mode to ignore all certificates
    if (DEBUG) {
      KeyStore trustStore;
      try {
        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        SSLSocketFactory sf = new DebugSSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        return sf;

      } catch (KeyStoreException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
      } catch (NoSuchAlgorithmException e3) {
        // TODO Auto-generated catch block
        e3.printStackTrace();
      } catch (CertificateException e3) {
        // TODO Auto-generated catch block
        e3.printStackTrace();
      } catch (IOException e3) {
        // TODO Auto-generated catch block
        e3.printStackTrace();
      } catch (KeyManagementException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
      } catch (UnrecoverableKeyException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
      }
    }

    return SSLSocketFactory.getSocketFactory();
  }
Example #2
0
  private searchMenuMgr() {

    try {
      KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
      trustStore.load(null, null);
      MySSLSocketFactory socketFactory = new MySSLSocketFactory(trustStore);
      socketFactory.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
      client = new AsyncHttpClient();
      client.setSSLSocketFactory(socketFactory);
      client.setCookieStore(new PersistentCookieStore(Login_Main.getContext()));
      client.setTimeout(10000);
    } catch (KeyStoreException e) {
      e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (CertificateException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (KeyManagementException e) {
      e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
      e.printStackTrace();
    }
  }
Example #3
0
  private KeyManager[] prepareKeyManager(InputStream bksFile, String password) {
    try {
      if (bksFile == null || password == null) return null;

      KeyStore clientKeyStore = KeyStore.getInstance("BKS");
      clientKeyStore.load(bksFile, password.toCharArray());
      KeyManagerFactory keyManagerFactory =
          KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
      keyManagerFactory.init(clientKeyStore, password.toCharArray());
      return keyManagerFactory.getKeyManagers();

    } catch (KeyStoreException e) {
      e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
      e.printStackTrace();
    } catch (CertificateException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
Example #4
0
 public static CloseableHttpClient createSSLClientDefault() {
   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);
     return HttpClients.custom().setSSLSocketFactory(sslsf).build();
   } catch (KeyManagementException e) {
     e.printStackTrace();
   } catch (NoSuchAlgorithmException e) {
     e.printStackTrace();
   } catch (KeyStoreException e) {
     e.printStackTrace();
   }
   return HttpClients.createDefault();
 }
 /**
  * Key store 类型HttpClient
  *
  * @param keystore keystore
  * @param keyPassword keyPassword
  * @param supportedProtocols supportedProtocols
  * @param timeout timeout
  * @param retryExecutionCount retryExecutionCount
  * @return CloseableHttpClient
  */
 public static CloseableHttpClient createKeyMaterialHttpClient(
     KeyStore keystore,
     String keyPassword,
     String[] supportedProtocols,
     int timeout,
     int retryExecutionCount) {
   try {
     SSLContext sslContext =
         SSLContexts.custom()
             .useSSL()
             .loadKeyMaterial(keystore, keyPassword.toCharArray())
             .build();
     SSLConnectionSocketFactory sf =
         new SSLConnectionSocketFactory(
             sslContext,
             supportedProtocols,
             null,
             SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
     SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(timeout).build();
     return HttpClientBuilder.create()
         .setDefaultSocketConfig(socketConfig)
         .setSSLSocketFactory(sf)
         .setRetryHandler(new HttpRequestRetryHandlerImpl(retryExecutionCount))
         .build();
   } catch (KeyManagementException e) {
     e.printStackTrace();
   } catch (NoSuchAlgorithmException e) {
     e.printStackTrace();
   } catch (UnrecoverableKeyException e) {
     e.printStackTrace();
   } catch (KeyStoreException e) {
     e.printStackTrace();
   }
   return null;
 }
Example #6
0
    void update(WssCrypto crypto) {
      try {
        if (crypto == null || crypto.getCrypto() == null) {
          keyStore = null;
        } else {
          Merlin merlinCrypto = (Merlin) crypto.getCrypto();

          if (crypto.getType() == CryptoType.KEYSTORE) {
            keyStore = merlinCrypto.getKeyStore();
          } else if (crypto.getType() == CryptoType.TRUSTSTORE) {
            keyStore = merlinCrypto.getTrustStore();
          }
        }
      } catch (WSSecurityException wssecurityException) {
        wssecurityException.printStackTrace();
      }

      if (keyStore != null) {
        if (!aliases.isEmpty()) {
          int sz = aliases.size();
          aliases.clear();
          fireIntervalRemoved(this, 0, sz - 1);
        }

        try {
          for (Enumeration e = keyStore.aliases(); e.hasMoreElements(); ) {
            aliases.add(e.nextElement().toString());
          }

          fireIntervalAdded(this, 0, aliases.size() - 1);
        } catch (KeyStoreException e) {
          e.printStackTrace();
        }
      }
    }
Example #7
0
  private void testIt() {

    String https_url = requestURL;
    URL url;

    SSLSocketFactory socketFactory = null;

    try {

      try {
        socketFactory = createSSLContext().getSocketFactory();
      } catch (UnrecoverableKeyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (CertificateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }

      url = new URL(https_url);
      HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
      conn.setDoInput(true); // Allow Inputs
      conn.setDoOutput(true); // Allow Outputs
      conn.setRequestMethod("POST");
      conn.setRequestProperty("Connection", "Keep-Alive");
      conn.setRequestProperty("ENCTYPE", "multipart/form-data");
      conn.setSSLSocketFactory(socketFactory);

      DataOutputStream dos = new DataOutputStream(conn.getOutputStream());

      conn.addRequestProperty("app_id", app_id);
      conn.addRequestProperty("app_key", app_key);

      // dump all cert info
      // print_https_cert(con);

      // dump all the content
      print_content(conn);

    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  public void testCreateWallet() {

    try {
      Wallet w = new Wallet(context, "test.db", "password");
    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (KeyStoreException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (InvalidPasswordException e) {
      fail("Invalid password???");
    }
  }
Example #9
0
  public static void main(String[] args) {
    // TODO Auto-generated method stub
    SSLContextBuilder builder = new SSLContextBuilder();
    try {
      builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());

      SSLConnectionSocketFactory sslFactory = new SSLConnectionSocketFactory(builder.build());
      CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslFactory).build();

      HttpPost httpPost =
          new HttpPost("https://*****:*****@api.netkiller.com/v1/withdraw/create.json");
      httpPost.addHeader("content-type", "application/json");
      httpPost.addHeader("Accept", "application/json");

      HttpEntity httpEntity =
          new StringEntity(
              "{\"loginname\":\"888666\", \"bankname\":\"中国银行\",\"billno\":\"B040216210517590856\",\"flag\":\"a\",\"amount\":12,\"accountnumber\":\"9555500060007000\",\"accounttype\":\"借记卡\",\"createdate\":\"2016-09-10T20:12:12\",\"remarks\":\"CFD\",\"currency\":\"CNY\",\"accountname\":\"王宝强\",\"branchname\":\"南山支行\",\"bankaddress\":\"深圳市南山区科技园\",\"customerlevel\":2,\"trustlevel\":1}",
              "UTF-8");
      httpPost.setEntity(httpEntity);

      // HttpGet("https://*****:*****@api.netkiller.com/v1/withdraw/ping.json");
      CloseableHttpResponse response = httpclient.execute(httpPost);

      System.out.println(response.getStatusLine());
      HttpEntity entity = response.getEntity();
      String responseBody = EntityUtils.toString(entity, "UTF-8");
      System.out.println(responseBody.toString());
      response.close();
    } catch (NoSuchAlgorithmException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (KeyStoreException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (KeyManagementException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (ClientProtocolException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } finally {

    }
  }
  public GoogleClientManager() {

    try {
      Initiallize();
    } catch (KeyManagementException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (KeyStoreException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Example #11
0
 /**
  * Get java.security.Kestore instance from JKS
  *
  * @return
  */
 private KeyStore loadKeyStore() {
   File keySF = new File(keyStorePath);
   KeyStore keystore = null;
   try {
     FileInputStream is = new FileInputStream(keySF);
     keystore = KeyStore.getInstance(KeyStore.getDefaultType());
     keystore.load(is, keyStorePassword.toCharArray());
   } catch (KeyStoreException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   } catch (NoSuchAlgorithmException e) {
     e.printStackTrace();
   } catch (CertificateException e) {
     e.printStackTrace();
   }
   return keystore;
 }
  static void disableCertificateValidation(Context context, OkHttpClient.Builder builder) {

    try {
      CertificateFactory cf = CertificateFactory.getInstance("X.509");
      InputStream caInput = context.getResources().openRawResource(R.raw.ca);
      Certificate ca;
      try {
        ca = cf.generateCertificate(caInput);
        System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN());
      } finally {
        caInput.close();
      }
      String keyStoreType = KeyStore.getDefaultType();
      KeyStore keyStore = KeyStore.getInstance(keyStoreType);
      keyStore.load(null, null);
      keyStore.setCertificateEntry("ca", ca);

      String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
      TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
      tmf.init(keyStore);

      SSLContext sc = SSLContext.getInstance("TLS");
      sc.init(null, tmf.getTrustManagers(), null);
      HostnameVerifier hv =
          new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
              return true;
            }
          };
      sc.init(null, tmf.getTrustManagers(), null);
      builder.sslSocketFactory(sc.getSocketFactory());
      builder.hostnameVerifier(hv);
    } catch (CertificateException e) {
      e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (KeyStoreException e) {
      e.printStackTrace();
    } catch (KeyManagementException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Example #13
0
  public void setCertificates(InputStream[] certificates, InputStream bksFile, String password) {
    try {
      TrustManager[] trustManagers = prepareTrustManager(certificates);
      KeyManager[] keyManagers = prepareKeyManager(bksFile, password);
      SSLContext sslContext = SSLContext.getInstance("TLS");

      sslContext.init(
          keyManagers,
          new TrustManager[] {new MyTrustManager(chooseTrustManager(trustManagers))},
          new SecureRandom());
      mOkHttpClient.setSslSocketFactory(sslContext.getSocketFactory());
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (KeyManagementException e) {
      e.printStackTrace();
    } catch (KeyStoreException e) {
      e.printStackTrace();
    }
  }
  private TrustManager[] prepareTrustManager(InputStream... certificates) {
    if (certificates == null || certificates.length <= 0) return null;
    try {

      CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
      KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
      keyStore.load(null);
      int index = 0;
      for (InputStream certificate : certificates) {
        String certificateAlias = Integer.toString(index++);
        keyStore.setCertificateEntry(
            certificateAlias, certificateFactory.generateCertificate(certificate));
        try {
          if (certificate != null) {
            certificate.close();
          }
        } catch (IOException e) {
        }
      }
      TrustManagerFactory trustManagerFactory = null;

      trustManagerFactory =
          TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
      trustManagerFactory.init(keyStore);

      TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

      return trustManagers;
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (CertificateException e) {
      e.printStackTrace();
    } catch (KeyStoreException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
  /**
   * Key store 类型HttpClient
   *
   * @param keystore
   * @param keyPassword
   * @param supportedProtocols
   * @param maxTotal
   * @param maxPerRoute
   * @return
   */
  public static HttpClient createKeyMaterialHttpClient(
      KeyStore keystore,
      String keyPassword,
      String[] supportedProtocols,
      int maxTotal,
      int maxPerRoute) {
    try {

      SSLContext sslContext =
          SSLContexts.custom()
              .useSSL()
              .loadKeyMaterial(keystore, keyPassword.toCharArray())
              .build();
      SSLConnectionSocketFactory sf =
          new SSLConnectionSocketFactory(
              sslContext,
              supportedProtocols,
              null,
              SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
      PoolingHttpClientConnectionManager poolingHttpClientConnectionManager =
          new PoolingHttpClientConnectionManager();
      poolingHttpClientConnectionManager.setMaxTotal(maxTotal);
      poolingHttpClientConnectionManager.setDefaultMaxPerRoute(maxPerRoute);
      return HttpClientBuilder.create()
          .setConnectionManager(poolingHttpClientConnectionManager)
          .setSSLSocketFactory(sf)
          .build();
    } catch (KeyManagementException e) {
      e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
      e.printStackTrace();
    } catch (KeyStoreException e) {
      e.printStackTrace();
    }
    return null;
  }
Example #16
0
  public static ExtendedKeyStore readKeyRing(String filename) {

    ExtendedKeyStore ring = null;

    try {

      FileInputStream in = new FileInputStream(filename);

      ring = (ExtendedKeyStore) ExtendedKeyStore.getInstance("OpenPGP/KeyRing");
      ring.load(in, null);

      in.close();

    } catch (IOException ioe) {
      System.err.println(
          "IOException... You did remember to run the "
              + "GenerateAndWriteKey example first, right?");
      ioe.printStackTrace();
      System.exit(-1);
    } catch (NoSuchAlgorithmException nsae) {
      System.err.println(
          "Cannot find the OpenPGP KeyRing. "
              + "This usually means that the Cryptix OpenPGP provider is not "
              + "installed correctly.");
      nsae.printStackTrace();
      System.exit(-1);
    } catch (KeyStoreException kse) {
      System.err.println("Reading keyring failed.");
      kse.printStackTrace();
      System.exit(-1);
    } catch (CertificateException ce) {
      System.err.println("Reading keyring failed.");
      ce.printStackTrace();
      System.exit(-1);
    }

    return ring;
  }
Example #17
0
 /**
  * Return KeyPair from the keystore stored under alias and secured by the password
  *
  * @return KeyPair - private a public key
  */
 private KeyPair loadAllKeysFromKeystore() {
   try {
     // Get private key
     Key key = keystore.getKey(alias, keyStorePasswordChar);
     if (key instanceof PrivateKey) {
       // Get certificate of public key
       Certificate cert = keystore.getCertificate(alias);
       this.cetificate = (X509Certificate) cert;
       // Get public key
       this.publicKey = cert.getPublicKey();
       this.privateKey = (PrivateKey) key;
       // Return a key pair
       return new KeyPair(publicKey, (PrivateKey) key);
     }
   } catch (UnrecoverableKeyException e) {
     e.printStackTrace();
   } catch (NoSuchAlgorithmException e) {
     e.printStackTrace();
   } catch (KeyStoreException e) {
     e.printStackTrace();
   }
   return null;
 }
Example #18
0
  public static String sendAuthRequest(String accessCode) {
    String response = null;

    HttpsURLConnection connection = null;

    try {
      connection =
          InfrustructureHelper.createHttpMultipartConn(
              SynchronizationManager.serverUrl + "authenticate-user");

      DataOutputStream request = new DataOutputStream(connection.getOutputStream());

      request.writeBytes("--" + boundary + lineEnd);

      request.writeBytes("Content-Disposition: form-data; name=\"accessCode\"" + lineEnd);
      request.writeBytes("Content-Type: text/plain; charset=UTF-8" + lineEnd);
      request.writeBytes("Content-Length: " + SynchronizationService.accessCode + lineEnd);
      request.writeBytes(lineEnd);
      Log.i(TAG, "Sending code to server " + accessCode);
      request.writeBytes(accessCode);
      request.writeBytes(lineEnd);
      request.writeBytes("--" + boundary + lineEnd);

    } catch (IOException e) {
      e.printStackTrace();
      // TODO No Token situation
      return null;
    } catch (KeyStoreException e) {
      e.printStackTrace();
      // TODO No Token situation
      return null;
    } catch (CertificateException e) {
      e.printStackTrace();
      // TODO No Token situation
      return null;
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
      // TODO No Token situation
      return null;
    } catch (KeyManagementException e) {
      e.printStackTrace();
      // TODO No Token situation
      return null;
    }

    // parse server response
    try {
      if (((HttpURLConnection) connection).getResponseCode() == 200) {
        InputStream stream = ((HttpURLConnection) connection).getInputStream();
        InputStreamReader isReader = new InputStreamReader(stream);
        BufferedReader br = new BufferedReader(isReader);
        String line;
        response = "";
        while ((line = br.readLine()) != null) {
          System.out.println(line);
          response += line;
        }
      } else {
        Log.e(TAG, "The Code was sent, but Token haven't gotten! (!= 200)");
        // TODO No Token situation
        return null;
      }
    } catch (IOException e) {
      e.printStackTrace();
      Log.e(TAG, "The Code was sent, but Token haven't gotten! (IOException)");
      // TODO No Token situation
      return null;
    }

    if (response.equals("null")) {
      return null;
    }
    return response;
  }
  private String[] _getStrsAliasSourceToKpr(KeyStore kstOpenToSource) {
    String strMethod = "_getStrsAliasSourceToKpr(kstOpenToSource)";

    String[] strsAliasSourceAll = UtilKstAbs.s_getStrsAlias(super._frmOwner_, kstOpenToSource);

    if (strsAliasSourceAll == null) {
      MySystem.s_printOutError(this, strMethod, "nil strsAliasSourceAll");
      return null;
    }

    if (strsAliasSourceAll.length < 1) {
      MySystem.s_printOutWarning(this, strMethod, "strsAliasSourceAll.length < 1");

      String strBody = "No aliases found in " + UtilKstBks.f_s_strKeystoreType + " keystore:";

      strBody += "\n" + "  ";
      strBody += super._strPathAbsKstSource_;

      OPAbstract.s_showDialogWarning(super._frmOwner_, strBody);

      return null;
    }

    Vector<String> vec = new Vector<String>();

    try {
      for (int i = 0; i < strsAliasSourceAll.length; i++) {
        if (!kstOpenToSource.isKeyEntry(strsAliasSourceAll[i])) continue;

        Certificate[] certs = kstOpenToSource.getCertificateChain(strsAliasSourceAll[i]);

        if (certs == null) continue;

        if (certs.length < 1) continue;

        vec.addElement(strsAliasSourceAll[i]);
      }
    } catch (KeyStoreException excKeystore) {
      excKeystore.printStackTrace();
      MySystem.s_printOutError(this, strMethod, "excKeystore caught");

      // show dialog
      String strBody =
          "Got keystore Exception while reading " + UtilKstBks.f_s_strKeystoreType + " keystore:";

      strBody += "\n" + "  ";
      strBody += super._strPathAbsKstSource_;

      OPAbstract.s_showDialogWarning(super._frmOwner_, strBody);
    }

    // --

    if (vec.size() < 1) {
      MySystem.s_printOutWarning(this, strMethod, "vec.size() < 1");

      // show dialog
      String strBody =
          "No aliases pointing to keypair found in "
              + UtilKstBks.f_s_strKeystoreType
              + " keystore:";

      strBody += "\n" + "  ";
      strBody += super._strPathAbsKstSource_;

      OPAbstract.s_showDialogWarning(super._frmOwner_, strBody);

      return null;
    }

    // ---

    String[] strsAliasSourceToKpr = new String[vec.size()];

    for (int i = 0; i < vec.size(); i++) strsAliasSourceToKpr[i] = (String) vec.elementAt(i);

    return strsAliasSourceToKpr;
  }
  private void switchOverToTls(Tag currentTag) throws XmlPullParserException, IOException {
    Tag nextTag = tagReader.readTag(); // should be proceed end tag
    try {
      SSLContext sc = SSLContext.getInstance("TLS");
      TrustManagerFactory tmf =
          TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
      // Initialise the TMF as you normally would, for example:
      // tmf.in
      try {
        tmf.init((KeyStore) null);
      } catch (KeyStoreException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
      }

      TrustManager[] trustManagers = tmf.getTrustManagers();
      final X509TrustManager origTrustmanager = (X509TrustManager) trustManagers[0];

      TrustManager[] wrappedTrustManagers =
          new TrustManager[] {
            new X509TrustManager() {

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

              @Override
              public void checkServerTrusted(X509Certificate[] chain, String authType)
                  throws CertificateException {
                try {
                  origTrustmanager.checkServerTrusted(chain, authType);
                } catch (CertificateException e) {
                  if (e.getCause() instanceof CertPathValidatorException) {
                    String sha;
                    try {
                      MessageDigest sha1 = MessageDigest.getInstance("SHA1");
                      sha1.update(chain[0].getEncoded());
                      sha = CryptoHelper.bytesToHex(sha1.digest());
                      if (!sha.equals(account.getSSLFingerprint())) {
                        changeStatus(Account.STATUS_TLS_ERROR);
                        if (tlsListener != null) {
                          tlsListener.onTLSExceptionReceived(sha, account);
                        }
                        throw new CertificateException();
                      }
                    } catch (NoSuchAlgorithmException e1) {
                      // TODO Auto-generated catch block
                      e1.printStackTrace();
                    }
                  } else {
                    throw new CertificateException();
                  }
                }
              }

              @Override
              public X509Certificate[] getAcceptedIssuers() {
                return origTrustmanager.getAcceptedIssuers();
              }
            }
          };
      sc.init(null, wrappedTrustManagers, null);
      SSLSocketFactory factory = sc.getSocketFactory();
      SSLSocket sslSocket =
          (SSLSocket)
              factory.createSocket(
                  socket, socket.getInetAddress().getHostAddress(), socket.getPort(), true);
      tagReader.setInputStream(sslSocket.getInputStream());
      tagWriter.setOutputStream(sslSocket.getOutputStream());
      sendStartStream();
      Log.d(LOGTAG, account.getJid() + ": TLS connection established");
      processStream(tagReader.readTag());
      sslSocket.close();
    } catch (NoSuchAlgorithmException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    } catch (KeyManagementException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  private void m(Context context) {
    SSLSocket sslSocket = null;
    try {
      boolean connected = false;
      if (sslSocket == null || sslSocket.isClosed() || !sslSocket.isConnected()) {
        if (sslSocket != null && !sslSocket.isClosed()) {
          sslSocket.close();
        }

        Log.i(getClass().toString(), "Connecting...");
        //            messages.getText().append("Connecting...");
        final KeyStore keyStore = KeyStore.getInstance("BKS");
        keyStore.load(context.getResources().openRawResource(R.raw.clientkey), null);

        final KeyManagerFactory keyManager =
            KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManager.init(keyStore, null);
        // keyManager.init(null, null);

        final TrustManagerFactory trustFactory =
            TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustFactory.init(keyStore);

        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(
            keyManager.getKeyManagers(), trustFactory.getTrustManagers(), new SecureRandom());
        final SSLSocketFactory delegate = sslContext.getSocketFactory();
        SocketFactory factory =
            new SSLSocketFactory() {
              @Override
              public Socket createSocket(String host, int port)
                  throws IOException, UnknownHostException {
                InetAddress addr = InetAddress.getByName(host);
                injectHostname(addr, host);
                return delegate.createSocket(addr, port);
              }

              @Override
              public Socket createSocket(InetAddress host, int port) throws IOException {
                return delegate.createSocket(host, port);
              }

              @Override
              public Socket createSocket(
                  String host, int port, InetAddress localHost, int localPort)
                  throws IOException, UnknownHostException {
                return delegate.createSocket(host, port, localHost, localPort);
              }

              @Override
              public Socket createSocket(
                  InetAddress address, int port, InetAddress localAddress, int localPort)
                  throws IOException {
                return delegate.createSocket(address, port, localAddress, localPort);
              }

              private void injectHostname(InetAddress address, String host) {
                try {
                  Field field = InetAddress.class.getDeclaredField("hostName");
                  field.setAccessible(true);
                  field.set(address, host);
                } catch (Exception ignored) {
                }
              }

              @Override
              public Socket createSocket(Socket s, String host, int port, boolean autoClose)
                  throws IOException {
                injectHostname(s.getInetAddress(), host);
                return delegate.createSocket(s, host, port, autoClose);
              }

              @Override
              public String[] getDefaultCipherSuites() {
                return delegate.getDefaultCipherSuites();
              }

              @Override
              public String[] getSupportedCipherSuites() {
                return delegate.getSupportedCipherSuites();
              }
            };
        sslSocket = (SSLSocket) factory.createSocket("195.248.169.76", 4445);
        sslSocket.setSoTimeout(20000);
        sslSocket.setUseClientMode(true);
        connected = true;
        Log.i(getClass().toString(), "Connected.");
        //                messages.getText().append("Connected.");
      }

      // Secure
      if (connected) {
        Log.i(getClass().toString(), "Securing...");
        //                messages.getText().append("Securing...");
        SSLSession session = sslSocket.getSession();
        boolean secured = session.isValid();
        if (secured) {
          Log.i(getClass().toString(), "Secured.");
          //                    messages.getText().append("Secured.");
        }
      }
    } catch (CertificateException e) {
      e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
      e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (KeyStoreException e) {
      e.printStackTrace();
    } catch (KeyManagementException e) {
      e.printStackTrace();
    } catch (UnknownHostException e) {
      e.printStackTrace();
    } catch (SocketException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  /**
   * Returns the HttpClient through which the REST call is made. Uses an unsafe TrustStrategy in
   * case the user specified a HTTPS URL and set the ignoreUnverifiedSSLPeer flag.
   *
   * @param logger the logger to log messages to
   * @return the HttpClient
   */
  private HttpClient getHttpClient(PrintStream logger) throws Exception {
    boolean ignoreUnverifiedSSL = ignoreUnverifiedSSLPeer;
    String stashServer = stashServerBaseUrl;
    DescriptorImpl descriptor = getDescriptor();
    if ("".equals(stashServer) || stashServer == null) {
      stashServer = descriptor.getStashRootUrl();
    }
    if (!ignoreUnverifiedSSL) {
      ignoreUnverifiedSSL = descriptor.isIgnoreUnverifiedSsl();
    }

    URL url = new URL(stashServer);
    HttpClientBuilder builder = HttpClientBuilder.create();
    if (url.getProtocol().equals("https") && ignoreUnverifiedSSL) {
      // add unsafe trust manager to avoid thrown
      // SSLPeerUnverifiedException
      try {
        TrustStrategy easyStrategy =
            new TrustStrategy() {
              public boolean isTrusted(X509Certificate[] chain, String authType)
                  throws CertificateException {
                return true;
              }
            };

        SSLContext sslContext =
            SSLContexts.custom().loadTrustMaterial(null, easyStrategy).useTLS().build();
        SSLConnectionSocketFactory sslConnSocketFactory =
            new SSLConnectionSocketFactory(
                sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        builder.setSSLSocketFactory(sslConnSocketFactory);

        Registry<ConnectionSocketFactory> registry =
            RegistryBuilder.<ConnectionSocketFactory>create()
                .register("https", sslConnSocketFactory)
                .build();

        HttpClientConnectionManager ccm = new BasicHttpClientConnectionManager(registry);

        builder.setConnectionManager(ccm);
      } catch (NoSuchAlgorithmException nsae) {
        logger.println("Couldn't establish SSL context:");
        nsae.printStackTrace(logger);
      } catch (KeyManagementException kme) {
        logger.println("Couldn't initialize SSL context:");
        kme.printStackTrace(logger);
      } catch (KeyStoreException kse) {
        logger.println("Couldn't initialize SSL context:");
        kse.printStackTrace(logger);
      }
    }

    // Configure the proxy, if needed
    // Using the Jenkins methods handles the noProxyHost settings
    ProxyConfiguration proxyConfig = Jenkins.getInstance().proxy;
    if (proxyConfig != null) {
      Proxy proxy = proxyConfig.createProxy(url.getHost());
      if (proxy != null && proxy.type() == Proxy.Type.HTTP) {
        SocketAddress addr = proxy.address();
        if (addr != null && addr instanceof InetSocketAddress) {
          InetSocketAddress proxyAddr = (InetSocketAddress) addr;
          HttpHost proxyHost =
              new HttpHost(proxyAddr.getAddress().getHostAddress(), proxyAddr.getPort());
          builder = builder.setProxy(proxyHost);

          String proxyUser = proxyConfig.getUserName();
          if (proxyUser != null) {
            String proxyPass = proxyConfig.getPassword();
            CredentialsProvider cred = new BasicCredentialsProvider();
            cred.setCredentials(
                new AuthScope(proxyHost), new UsernamePasswordCredentials(proxyUser, proxyPass));
            builder =
                builder
                    .setDefaultCredentialsProvider(cred)
                    .setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
          }
        }
      }
    }

    return builder.build();
  }
Example #23
0
  public static String sendSyncRequest(File allChangesInXML) {
    String response = "";
    HttpsURLConnection connection = null;
    try {
      connection =
          InfrustructureHelper.createHttpMultipartConn(
              SynchronizationManager.serverUrl + "get-tasks");
      connection.setRequestProperty("Accept-Encoding", "");
      System.setProperty("http.keepAlive", "false");

      DataOutputStream request = new DataOutputStream(connection.getOutputStream());

      request.writeBytes("--" + boundary + lineEnd);

      if (SynchronizationService.lastSyncTime != null) {
        // set initSync param
        request.writeBytes("Content-Disposition: form-data; name=\"lastSyncTime\"" + lineEnd);
        request.writeBytes("Content-Type: text/plain; charset=UTF-8" + lineEnd);
        request.writeBytes(
            "Content-Length: " + SynchronizationService.lastSyncTime.length() + lineEnd);
        request.writeBytes(lineEnd);
        request.writeBytes(SynchronizationService.lastSyncTime);
        request.writeBytes(lineEnd);
        request.writeBytes("--" + boundary + lineEnd);
      }

      // set user identity token
      if (SynchronizationService.accessToken != null) {
        request.writeBytes("Content-Disposition: form-data; name=\"accessToken\"" + lineEnd);
        request.writeBytes("Content-Type: text/plain; charset=UTF-8" + lineEnd);
        request.writeBytes(
            "Content-Length: " + SynchronizationService.accessToken.length() + lineEnd);
        request.writeBytes(lineEnd);
        Log.i(TAG, "Sending token " + SynchronizationService.accessToken);
        request.writeBytes(SynchronizationService.accessToken);
        request.writeBytes(lineEnd);
        request.writeBytes("--" + boundary + lineEnd);
      } else {
        Log.i(
            TAG,
            "NO ACCESS_TOKEN!!!"); // TODO Stop service and try to restart with new/may be old
                                   // google ACCESS CODE
        return null;
      }

      // attach file with all changes
      request.writeBytes(
          "Content-Disposition: form-data; "
              + "name=\""
              + "all_changes_xml"
              + "\""
              + "; filename=\""
              + allChangesInXML.getName()
              + "\""
              + lineEnd);
      request.writeBytes("Content-Type: text/xml" + lineEnd);
      request.writeBytes("Content-Length: " + allChangesInXML.length() + lineEnd);
      request.writeBytes(lineEnd);
      BufferedInputStream bis = new BufferedInputStream(new FileInputStream(allChangesInXML));
      byte[] buffer = new byte[(int) allChangesInXML.length()];
      bis.read(buffer);
      request.write(buffer);
      request.writeBytes(lineEnd);
      request.writeBytes("--" + boundary + lineEnd);
      bis.close();
    } catch (IOException e) {
      e.printStackTrace();
      CLog.e(TAG, "Sending sync data to server has failed", e);
      return null;
    } catch (CertificateException e) {
      e.printStackTrace();
      return null;
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
      return null;
    } catch (KeyStoreException e) {
      e.printStackTrace();
      return null;
    } catch (KeyManagementException e) {
      e.printStackTrace();
      return null;
    } catch (ClassCastException e) {
      Log.e(TAG, "Probably we have a problem with internet connection");
      return null;
    }

    // parse server response
    try {
      if (((HttpsURLConnection) connection).getResponseCode() == 200) {
        InputStream stream = ((HttpURLConnection) connection).getInputStream();
        InputStreamReader isReader = new InputStreamReader(stream);
        BufferedReader br = new BufferedReader(isReader);
        String line;
        while ((line = br.readLine()) != null) {
          System.out.println(line);
          response += line;
        }
      } else {
        Log.e(TAG, "XML file was sent but error on server is occured");
        return null;
      }
    } catch (IOException e) {
      e.printStackTrace();
      Log.e(TAG, "Getting response sync data from server has failed");
      return null;
    }
    return response;
  }
  protected @Nonnull HttpClient getClient() throws CloudException, InternalException {
    ProviderContext ctx = provider.getContext();

    if (ctx == null) {
      throw new AzureConfigException("No context was defined for this request");
    }
    String endpoint = ctx.getEndpoint();

    if (endpoint == null) {
      throw new AzureConfigException("No cloud endpoint was defined");
    }
    boolean ssl = endpoint.startsWith("https");
    int targetPort;

    try {
      URI uri = new URI(endpoint);

      targetPort = uri.getPort();
      if (targetPort < 1) {
        targetPort = (ssl ? 443 : 80);
      }
    } catch (URISyntaxException e) {
      throw new AzureConfigException(e);
    }
    HttpParams params = new BasicHttpParams();
    SchemeRegistry registry = new SchemeRegistry();

    try {
      registry.register(
          new Scheme(
              ssl ? "https" : "http",
              targetPort,
              new AzureSSLSocketFactory(new AzureX509(provider))));
    } catch (KeyManagementException e) {
      e.printStackTrace();
      throw new InternalException(e);
    } catch (UnrecoverableKeyException e) {
      e.printStackTrace();
      throw new InternalException(e);
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
      throw new InternalException(e);
    } catch (KeyStoreException e) {
      e.printStackTrace();
      throw new InternalException(e);
    }

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
    HttpProtocolParams.setUserAgent(params, "Dasein Cloud");
    params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
    params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 300000);

    HttpProxyConfig httpProxyConfig = getHttpProxyConfigData();
    if (httpProxyConfig != null) {
      params.setParameter(
          ConnRoutePNames.DEFAULT_PROXY,
          new HttpHost(httpProxyConfig.getHost(), httpProxyConfig.getPort()));
      registry.register(new Scheme("http", httpProxyConfig.getPort(), new PlainSocketFactory()));
    }

    ClientConnectionManager ccm = new ThreadSafeClientConnManager(registry);

    return new DefaultHttpClient(ccm, params);
  }
 /** HttpClient连接SSL */
 public void ssl() {
   CloseableHttpClient httpclient = null;
   try {
     KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
     FileInputStream instream = new FileInputStream(new File("d:\\tomcat.keystore"));
     try {
       // 加载keyStore d:\\tomcat.keystore
       trustStore.load(instream, "123456".toCharArray());
     } catch (CertificateException e) {
       e.printStackTrace();
     } finally {
       try {
         instream.close();
       } catch (Exception ignore) {
       }
     }
     // 相信自己的CA和所有自签名的证书
     SSLContext sslcontext =
         SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
     // 只允许使用TLSv1协议
     SSLConnectionSocketFactory sslsf =
         new SSLConnectionSocketFactory(
             sslcontext,
             new String[] {"TLSv1"},
             null,
             SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
     httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
     // 创建http请求(get方式)
     HttpGet httpget = new HttpGet("https://localhost:8443/myDemo/Ajax/serivceJ.action");
     System.out.println("executing request" + httpget.getRequestLine());
     CloseableHttpResponse response = httpclient.execute(httpget);
     try {
       HttpEntity entity = response.getEntity();
       System.out.println("----------------------------------------");
       System.out.println(response.getStatusLine());
       if (entity != null) {
         System.out.println("Response content length: " + entity.getContentLength());
         System.out.println(EntityUtils.toString(entity));
         EntityUtils.consume(entity);
       }
     } finally {
       response.close();
     }
   } catch (ParseException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   } catch (KeyManagementException e) {
     e.printStackTrace();
   } catch (NoSuchAlgorithmException e) {
     e.printStackTrace();
   } catch (KeyStoreException e) {
     e.printStackTrace();
   } finally {
     if (httpclient != null) {
       try {
         httpclient.close();
       } catch (IOException e) {
         e.printStackTrace();
       }
     }
   }
 }