@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);
    }
  /**
   * ִ��http���á�true:�ɹ� false:ʧ��
   *
   * @return boolean
   */
  public boolean call() {

    boolean isRet = false;

    // http
    if (null == this.caFile && null == this.certFile) {
      try {
        this.callHttp();
        isRet = true;
      } catch (IOException e) {
        this.errInfo = e.getMessage();
      }
      return isRet;
    }

    // https
    try {
      this.callHttps();
      isRet = true;
    } catch (UnrecoverableKeyException e) {
      this.errInfo = e.getMessage();
    } catch (KeyManagementException e) {
      this.errInfo = e.getMessage();
    } catch (CertificateException e) {
      this.errInfo = e.getMessage();
    } catch (KeyStoreException e) {
      this.errInfo = e.getMessage();
    } catch (NoSuchAlgorithmException e) {
      this.errInfo = e.getMessage();
    } catch (IOException e) {
      this.errInfo = e.getMessage();
    }

    return isRet;
  }
  private EasySSLSocketFactory() {
    super();
    TrustManager[] tm =
        new TrustManager[] {
          new X509TrustManager() {

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

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

            @Override
            public X509Certificate[] getAcceptedIssuers() {
              return new X509Certificate[0];
            }
          }
        };
    try {
      this.sslcontext = SSLContext.getInstance(SSLSocketFactory.TLS);
      this.sslcontext.init(null, tm, new SecureRandom());
      this.socketfactory = this.sslcontext.getSocketFactory();
    } catch (NoSuchAlgorithmException e) {
      Log.e(this.getClass().getName(), e.getMessage());
    } catch (KeyManagementException e) {
      Log.e(this.getClass().getName(), e.getMessage());
    }
  }
 private SSLSocketFactory getSSLSocketFactory(String keyStoreName, String password) {
   KeyStore ks = getKeyStore(keyStoreName, password);
   KeyManagerFactory keyManagerFactory = null;
   try {
     keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
     keyManagerFactory.init(ks, password.toCharArray());
     SSLContext context = SSLContext.getInstance("TLS");
     context.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom());
     return context.getSocketFactory();
   } catch (NoSuchAlgorithmException e) {
     logger.error(e.getMessage(), e);
     throw new RuntimeException(e.getMessage(), e);
   } catch (KeyStoreException e) {
     logger.error(e.getMessage(), e);
     throw new RuntimeException(e.getMessage(), e);
   } catch (UnrecoverableKeyException e) {
     logger.error(e.getMessage(), e);
     throw new RuntimeException(e.getMessage(), e);
   } catch (KeyManagementException e) {
     logger.error(e.getMessage(), e);
     throw new RuntimeException(e.getMessage(), e);
   }
 }
  private void sslFileTransfer(String filename) {
    try {
      KeyStore trusted = KeyStore.getInstance("BKS");
      // Get the raw resource, which contains the keystore with
      // your trusted certificates (root and any intermediate certs)
      InputStream in =
          context.getResources().openRawResource(tracker.springversion1.R.raw.mykeystore);
      trusted.load(in, "mysecret".toCharArray());

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

      // Create an SSLContext that uses our TrustManager
      SSLContext context = SSLContext.getInstance("TLS");
      context.init(null, tmf.getTrustManagers(), null);

      URL url = new URL(host);
      HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
      urlConnection.setSSLSocketFactory(context.getSocketFactory());

      transfer(urlConnection, filename);

      //			SSLSocketFactory sf = new SSLSocketFactory(trusted);
      //			// Hostname verification from certificate
      //			// http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d4e506
      //			sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
      //
      //			Socket sslsocket = sf.createSocket();
      //			sslsocket.setKeepAlive(true);
      //
      //			InetSocketAddress address = new InetSocketAddress(host, 443);
      //			sslsocket.connect(address);
      //
      //			OutputStream sout = sslsocket.getOutputStream();

    } catch (KeyStoreException e) {
      Log.v("mark", "KeyStoreException:" + e.getMessage());
    } catch (NoSuchAlgorithmException e) {
      Log.v("mark", "NoSuchAlgorithmException:" + e.getMessage());
    } catch (CertificateException e) {
      Log.v("mark", "CertificateException:" + e.getMessage());
    } catch (IOException e) {
      Log.v("mark", "IOException:" + e.getMessage());
    } catch (KeyManagementException e) {
      Log.v("mark", "KeyManagementException:" + e.getMessage());
    }
  }
  private SSLContext createSSLContext() throws ClientSslContextFactoryException {
    try {
      final SSLContext sslcontext = SSLContext.getInstance(SOCKET_ALGORITHM);
      sslcontext.init(null, new TrustSelfSignedStrategy[] {}, new SecureRandom());

      return sslcontext;
    } catch (NoSuchAlgorithmException e) {
      throw new ClientSslContextFactoryException(
          String.format(
              "Failed to create an SSL context that supports algorithm %s: %s",
              SOCKET_ALGORITHM, e.getMessage()),
          e);
    } catch (KeyManagementException e) {
      throw new ClientSslContextFactoryException(
          String.format("Failed to initialize an SSL context: %s", e.getMessage()), e);
    }
  }
  /**
   * Creates the SSL context needed to create the socket factory used by this factory. The key and
   * trust store parameters are optional. If they are null then the JRE defaults will be used.
   *
   * @return the newly created SSL context
   * @throws ClientSslContextFactoryException if an error is detected loading the specified key or
   *     trust stores
   */
  private SSLContext createSSLContext() throws ClientSslContextFactoryException {
    final KeyManager[] keyManagers = this.keyStore != null ? createKeyManagers() : null;
    final TrustManager[] trustManagers = this.trustStore != null ? createTrustManagers() : null;

    try {
      final SSLContext sslcontext = SSLContext.getInstance(SOCKET_ALGORITHM);

      sslcontext.init(keyManagers, trustManagers, null);

      return sslcontext;
    } catch (NoSuchAlgorithmException e) {
      throw new ClientSslContextFactoryException(
          String.format(
              "Failed to create an SSL context that supports algorithm %s: %s",
              SOCKET_ALGORITHM, e.getMessage()),
          e);
    } catch (KeyManagementException e) {
      throw new ClientSslContextFactoryException(
          String.format("Failed to initialize an SSL context: %s", e.getMessage()), e);
    }
  }
Ejemplo n.º 8
0
  public PushManager get(Product product) {

    if (StringUtils.isBlank(product.getDevCertPath())
        || StringUtils.isBlank(product.getDevCertPass())
        || StringUtils.isBlank(product.getCertPath())
        || StringUtils.isBlank(product.getCertPass())) {
      logger.error("Product iOS Push Service Miss Cert Path and Password. {}", product);
      return null;
    }

    PushManager service = mapping.get(product.getId());
    if (service == null) {

      ApnsEnvironment apnsEnvironment = null;
      SSLContext sslContext = null;

      try {
        if (sandBox) {
          apnsEnvironment = ApnsEnvironment.getSandboxEnvironment();
          sslContext =
              SSLContextUtil.createDefaultSSLContext(
                  product.getDevCertPath(), product.getDevCertPass());
        } else {
          apnsEnvironment = ApnsEnvironment.getProductionEnvironment();
          sslContext =
              SSLContextUtil.createDefaultSSLContext(product.getCertPath(), product.getCertPass());
        }
      } catch (KeyStoreException e) {
        logger.error(e.getMessage(), e);
      } catch (NoSuchAlgorithmException e) {
        logger.error(e.getMessage(), e);
      } catch (CertificateException e) {
        logger.error(e.getMessage(), e);
      } catch (UnrecoverableKeyException e) {
        logger.error(e.getMessage(), e);
      } catch (KeyManagementException e) {
        logger.error(e.getMessage(), e);
      } catch (IOException e) {
        logger.error(e.getMessage(), e);
      }

      PushManagerConfiguration configuration = new PushManagerConfiguration();
      configuration.setConcurrentConnectionCount(1);

      final PushManager<SimpleApnsPushNotification> pushManager =
          new PushManager<SimpleApnsPushNotification>(
              apnsEnvironment,
              sslContext,
              null, // Optional: custom event loop group
              null, // Optional: custom ExecutorService for calling listeners
              null, // Optional: custom BlockingQueue implementation
              configuration,
              "ApnsPushManager-" + product.getId());

      pushManager.registerRejectedNotificationListener(new PushRejectedNotificationListener());
      pushManager.registerFailedConnectionListener(new PushFailedConnectionListener());

      pushManager.start();

      //             ApnsServiceBuilder builder =  APNS.newService();
      //            if (sandBox){
      //                builder.withCert(product.getDevCertPath(), product.getDevCertPass());
      //                builder.withSandboxDestination();
      //            }else{
      //                builder.withCert(product.getCertPath(), product.getCertPass());
      //                builder.withProductionDestination();
      //            }
      //            service =
      // builder.asPool(10).withCacheLength(Integer.MAX_VALUE).withDelegate(delegateAdapter).asQueued().build();

      mapping.put(product.getId(), pushManager);
      service = pushManager;
    }

    return service;
  }