protected AdditionalKeyStoresTrustManager(KeyStore... additionalkeyStores) {
      final ArrayList<TrustManagerFactory> factories = new ArrayList<TrustManagerFactory>();

      try {
        // The default Trustmanager with default keystore
        final TrustManagerFactory original =
            TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        original.init((KeyStore) null);
        factories.add(original);

        for (KeyStore keyStore : additionalkeyStores) {
          final TrustManagerFactory additionalCerts =
              TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
          additionalCerts.init(keyStore);
          factories.add(additionalCerts);
        }

      } catch (Exception e) {
        throw new RuntimeException(e);
      }

      /*
       * Iterate over the returned trustmanagers, and hold on
       * to any that are X509TrustManagers
       */
      for (TrustManagerFactory tmf : factories)
        for (TrustManager tm : tmf.getTrustManagers())
          if (tm instanceof X509TrustManager) x509TrustManagers.add((X509TrustManager) tm);

      if (x509TrustManagers.size() == 0)
        throw new RuntimeException("Couldn't find any X509TrustManagers");
    }
Example #2
0
  public TLSServer(KeyStore keyStore, String password, String protocol, int port)
      throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException,
          UnrecoverableKeyException, KeyManagementException {

    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
    keyManagerFactory.init(keyStore, password.toCharArray());
    KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();

    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
    trustManagerFactory.init(keyStore);
    TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
    sslContext = SSLContext.getInstance(protocol);
    sslContext.init(keyManagers, trustManagers, null);

    cipherSuites = sslContext.getServerSocketFactory().getSupportedCipherSuites();

    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("Provider: " + sslContext.getProvider());
      LOGGER.debug(
          "Supported cipher suites ("
              + sslContext.getServerSocketFactory().getSupportedCipherSuites().length
              + ")");
      for (String c : sslContext.getServerSocketFactory().getSupportedCipherSuites()) {
        LOGGER.debug(" " + c);
      }
    }

    this.port = port;
    LOGGER.info("SSL Server successfully initialized!");
  }
Example #3
0
 /**
  * Returns SSLContext with TESTED_SECURITY_PROTOCOL protocol and sets up keys.
  *
  * @return - SSLContext with a protocol specified by TESTED_SECURITY_PROTOCOL.
  */
 public static SSLContext getContext() {
   try {
     java.security.Security.setProperty("jdk.tls.disabledAlgorithms", "");
     java.security.Security.setProperty("jdk.certpath.disabledAlgorithms", "");
     KeyStore ks = KeyStore.getInstance("JKS");
     KeyStore ts = KeyStore.getInstance("JKS");
     char[] passphrase = PASSWD.toCharArray();
     try (FileInputStream keyFileStream = new FileInputStream(KEY_FILE_NAME)) {
       ks.load(keyFileStream, passphrase);
     }
     try (FileInputStream trustFileStream = new FileInputStream(TRUST_FILE_NAME)) {
       ts.load(trustFileStream, passphrase);
     }
     KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
     kmf.init(ks, passphrase);
     TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
     tmf.init(ts);
     SSLContext sslCtx = SSLContext.getInstance(TESTED_SECURITY_PROTOCOL);
     sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
     return sslCtx;
   } catch (KeyStoreException
       | IOException
       | NoSuchAlgorithmException
       | CertificateException
       | UnrecoverableKeyException
       | KeyManagementException ex) {
     throw new Error("Unexpected exception", ex);
   }
 }
Example #4
0
  public static Map<String, Object> createSslConfig(
      Mode mode,
      File keyStoreFile,
      Password password,
      Password keyPassword,
      File trustStoreFile,
      Password trustStorePassword) {
    Map<String, Object> sslConfigs = new HashMap<>();
    sslConfigs.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL"); // kafka security protocol
    sslConfigs.put(SslConfigs.SSL_PROTOCOL_CONFIG, "TLSv1.2"); // protocol to create SSLContext

    if (mode == Mode.SERVER || (mode == Mode.CLIENT && keyStoreFile != null)) {
      sslConfigs.put(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG, keyStoreFile.getPath());
      sslConfigs.put(SslConfigs.SSL_KEYSTORE_TYPE_CONFIG, "JKS");
      sslConfigs.put(
          SslConfigs.SSL_KEYMANAGER_ALGORITHM_CONFIG, TrustManagerFactory.getDefaultAlgorithm());
      sslConfigs.put(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG, password);
      sslConfigs.put(SslConfigs.SSL_KEY_PASSWORD_CONFIG, keyPassword);
    }

    sslConfigs.put(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, trustStoreFile.getPath());
    sslConfigs.put(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, trustStorePassword);
    sslConfigs.put(SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG, "JKS");
    sslConfigs.put(
        SslConfigs.SSL_TRUSTMANAGER_ALGORITHM_CONFIG, TrustManagerFactory.getDefaultAlgorithm());

    List<String> enabledProtocols = new ArrayList<>();
    enabledProtocols.add("TLSv1.2");
    sslConfigs.put(SslConfigs.SSL_ENABLED_PROTOCOLS_CONFIG, enabledProtocols);

    return sslConfigs;
  }
Example #5
0
 MyX509TrustManager() throws java.security.GeneralSecurityException {
   TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
   KeyStore ks = KeyStore.getInstance("JKS");
   CertificateFactory cf = CertificateFactory.getInstance("X.509");
   try {
     ks.load(null, null);
     File cacert = new File(cafile);
     if (!cacert.exists() || !cacert.canRead()) return;
     InputStream caStream = new FileInputStream(cafile);
     X509Certificate ca = (X509Certificate) cf.generateCertificate(caStream);
     ks.setCertificateEntry("CA", ca);
     PKIXBuilderParameters params = new PKIXBuilderParameters(ks, new X509CertSelector());
     File crlcert = new File(crlfile);
     if (!crlcert.exists() || !crlcert.canRead()) {
       params.setRevocationEnabled(false);
     } else {
       InputStream crlStream = new FileInputStream(crlfile);
       Collection<? extends CRL> crls = cf.generateCRLs(crlStream);
       CertStoreParameters csp = new CollectionCertStoreParameters(crls);
       CertStore store = CertStore.getInstance("Collection", csp);
       params.addCertStore(store);
       params.setRevocationEnabled(true);
     }
     tmf.init(new CertPathTrustManagerParameters(params));
   } catch (java.io.FileNotFoundException e) {
     vlog.error(e.toString());
   } catch (java.io.IOException e) {
     vlog.error(e.toString());
   }
   tm = (X509TrustManager) tmf.getTrustManagers()[0];
 }
Example #6
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;
  }
  /** Creates a new TlsSocketFactory */
  public TlsSocketFactory(TlsContext tls_context)
      throws java.security.KeyStoreException, java.security.KeyManagementException,
          java.security.UnrecoverableKeyException, java.security.NoSuchAlgorithmException {
    KeyStore ks = tls_context.getKeyStore();
    // get key managers
    KeyManagerFactory key_manager_factory =
        KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    key_manager_factory.init(ks, TlsContext.DEFAULT_PASSWORD);
    KeyManager[] key_managers = key_manager_factory.getKeyManagers();
    TrustManager[] trust_managers;
    // get trust managers
    if (tls_context.isTrustAll()) {
      X509TrustManager trust_all =
          new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
              return new X509Certificate[0];
            }

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

            public void checkServerTrusted(X509Certificate[] certs, String auth_type) {}
          };
      trust_managers = new TrustManager[] {trust_all};
    } else {
      TrustManagerFactory trust_manager_factory =
          TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
      trust_manager_factory.init(ks);
      trust_managers = trust_manager_factory.getTrustManagers();
    }
    // install only the trust managers
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(key_managers, trust_managers, null /*new java.security.SecureRandom()*/);
    // get the socket factory
    ssl_factory = sc.getSocketFactory();
  }
  private Client createClient(
      Environment environment,
      JerseyClientConfiguration configuration,
      String federationName,
      FederatedPeer peer)
      throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException,
          CertificateException {
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("X509");
    trustManagerFactory.init(initializeTrustStore(peer.getName(), peer.getCertificate()));

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(
        null, trustManagerFactory.getTrustManagers(), SecureRandom.getInstance("SHA1PRNG"));

    SSLConnectionSocketFactory sslConnectionSocketFactory =
        new SSLConnectionSocketFactory(sslContext, new DefaultHostnameVerifier());
    Registry<ConnectionSocketFactory> registry =
        RegistryBuilder.<ConnectionSocketFactory>create()
            .register("https", sslConnectionSocketFactory)
            .build();

    Client client =
        new JerseyClientBuilder(environment)
            .using(configuration)
            .using(registry)
            .build("FederatedClient");

    client.property(ClientProperties.CONNECT_TIMEOUT, 5000);
    client.property(ClientProperties.READ_TIMEOUT, 10000);
    client.property(ClientProperties.REQUEST_ENTITY_PROCESSING, RequestEntityProcessing.BUFFERED);
    client.register(HttpAuthenticationFeature.basic(federationName, peer.getAuthenticationToken()));

    return client;
  }
  /** connection with SSL */
  public void sslConnection() {
    String keyStoreLocation = properties.getProperty(IbmMqConstants.SSL_KEYSTORE_LOCATION);
    String keyStoreType = properties.getProperty(IbmMqConstants.SSL_KEYSTORE_TYPE);
    String keyStorePassword = properties.getProperty(IbmMqConstants.SSL_KEYSTORE_PASSWORD);
    String trustStoreLocation = properties.getProperty(IbmMqConstants.SSL_TRUSTSTORE_LOCATION);
    String trustStoreType = properties.getProperty(IbmMqConstants.SSL_TRUSTSTORE_TYPE);
    String sslVersion = properties.getProperty(IbmMqConstants.SSL_VERSION);
    String sslFipsRequired = properties.getProperty(IbmMqConstants.SSL_FIPS);
    String sslCipherSuite = properties.getProperty(IbmMqConstants.SSL_CIPHERSUITE);
    boolean sslFips = Boolean.parseBoolean(sslFipsRequired);
    try {
      char[] keyPassphrase = keyStorePassword.toCharArray();
      KeyStore ks = KeyStore.getInstance(keyStoreType);
      ks.load(new FileInputStream(keyStoreLocation), keyPassphrase);
      KeyStore trustStore = KeyStore.getInstance(trustStoreType);
      trustStore.load(new FileInputStream(trustStoreLocation), null);

      TrustManagerFactory trustManagerFactory =
          TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
      KeyManagerFactory keyManagerFactory =
          KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());

      trustManagerFactory.init(trustStore);
      keyManagerFactory.init(ks, keyPassphrase);
      SSLContext sslContext = SSLContext.getInstance(sslVersion);
      sslContext.init(
          keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
      mqProperties.put(MQConstants.SSL_SOCKET_FACTORY_PROPERTY, sslContext);
      mqProperties.put(MQConstants.SSL_FIPS_REQUIRED_PROPERTY, sslFips);
      mqProperties.put(MQConstants.SSL_CIPHER_SUITE_PROPERTY, sslCipherSuite);
    } catch (Exception ex) {
      handleException(ex.getMessage());
    }
  }
Example #10
0
  MyX509TrustManager(File trustStore, char[] password) throws Exception {
    // create a "default" JSSE X509TrustManager.

    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(new FileInputStream(trustStore), password);

    TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
    tmf.init(ks);

    TrustManager tms[] = tmf.getTrustManagers();

    /*
     * Iterate over the returned trust managers, look
     * for an instance of X509TrustManager.  If found,
     * use that as our "default" trust manager.
     */
    for (TrustManager tm : tms) {
      if (tm instanceof X509TrustManager) {
        pkixTrustManager = (X509TrustManager) tm;
        return;
      }
    }

    /*
     * Find some other way to initialize, or else we have to fail the
     * constructor.
     */
    throw new Exception("Couldn't initialize");
  }
 private static SSLContext createSSLContext(
     final String algorithm,
     final KeyStore keystore,
     final String keystorePassword,
     final KeyStore truststore,
     final SecureRandom random,
     final TrustStrategy trustStrategy)
     throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException,
         KeyManagementException {
   String algo = algorithm != null ? algorithm : TLS;
   KeyManagerFactory kmfactory =
       KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
   kmfactory.init(keystore, keystorePassword != null ? keystorePassword.toCharArray() : null);
   KeyManager[] keymanagers = kmfactory.getKeyManagers();
   TrustManagerFactory tmfactory =
       TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
   tmfactory.init(truststore);
   TrustManager[] trustmanagers = tmfactory.getTrustManagers();
   if (trustmanagers != null && trustStrategy != null) {
     for (int i = 0; i < trustmanagers.length; i++) {
       TrustManager tm = trustmanagers[i];
       if (tm instanceof X509TrustManager) {
         trustmanagers[i] = new TrustManagerDecorator((X509TrustManager) tm, trustStrategy);
       }
     }
   }
   SSLContext sslcontext = SSLContext.getInstance(algo);
   sslcontext.init(keymanagers, trustmanagers, random);
   return sslcontext;
 }
  /**
   * Loads the public certificate of the server in to a {@link TrustManager} so that the client
   * trusts the server when it connects.
   *
   * @param certificateStoreFile the file to load the certificate from.
   */
  public static TrustManager[] loadServerCertificates(String certificateStoreFile)
      throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
    try {
      InputStream trustStoreIS = new FileInputStream(certificateStoreFile);
      char[] trustStorePassphrase = "storepass".toCharArray();
      KeyStore ksTrust = KeyStore.getInstance("JKS");
      ksTrust.load(trustStoreIS, trustStorePassphrase);

      // TrustManager decides which certificate authorities to use.
      String defaultTrustManagerAlgorithm = TrustManagerFactory.getDefaultAlgorithm();

      LOG.info("Default trust manager algorithm is {}", defaultTrustManagerAlgorithm);
      TrustManagerFactory tmf = TrustManagerFactory.getInstance(defaultTrustManagerAlgorithm);
      tmf.init(ksTrust);

      TrustManager[] tm = tmf.getTrustManagers();
      LOG.info("Loaded {} trust managers", tm.length);

      return tm;
    } catch (FileNotFoundException fnfe) {
      // If they keystore doesn't exist, then return empty so we can try out what works with NO
      // keystore
      LOG.error("Unable to find store file {}", certificateStoreFile);
      throw fnfe;
    }
  }
Example #13
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;
  }
  private SSLSocketFactory createSocketFactory() {

    // Load CAs from an InputStream
    // (could be from a resource or ByteArrayInputStream or ...)
    try {

      // Create a KeyStore containing our trusted CAs
      String keyStoreType = "BKS";
      KeyStore keyStore = KeyStore.getInstance(keyStoreType);
      // keyStore.load(ksInput, "recsports".toCharArray());

      // Create a KeyManager
      String kmfAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
      KeyManagerFactory kmf = KeyManagerFactory.getInstance(kmfAlgorithm);
      kmf.init(keyStore, "recsports".toCharArray());

      // Create a TrustManager that trusts the CAs in our KeyStore
      String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
      TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
      tmf.init(keyStore);

      //            ksInput.close();

      return new CipherExtendedSSLSocketFactory(kmf, tmf);

    } catch (Exception e) {
      Log.e(LOG_TAG, e.getMessage());
      return null;
    }
  }
Example #15
0
  private void initTrustManagerFactory() throws InitialisationException {
    if (null != trustStoreName) {
      trustStorePassword = null == trustStorePassword ? "" : trustStorePassword;

      KeyStore trustStore;
      try {
        trustStore = KeyStore.getInstance(trustStoreType);
        InputStream is = IOUtils.getResourceAsStream(trustStoreName, getClass());
        if (null == is) {
          throw new FileNotFoundException(
              "Failed to load truststore from classpath or local file: " + trustStoreName);
        }
        trustStore.load(is, trustStorePassword.toCharArray());
      } catch (Exception e) {
        throw new InitialisationException(
            CoreMessages.failedToLoad("TrustStore: " + trustStoreName), e, this);
      }

      try {
        trustManagerFactory = TrustManagerFactory.getInstance(trustManagerAlgorithm);
        trustManagerFactory.init(trustStore);
      } catch (Exception e) {
        throw new InitialisationException(
            CoreMessages.failedToLoad("Trust Manager (" + trustManagerAlgorithm + ")"), e, this);
      }
    }
  }
Example #16
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 #17
0
 /** @return trust managers loaded for this service. */
 public synchronized TrustManager[] getTrustManagers() throws GeneralSecurityException {
   // Build a new set of TrustManagers based on the KeyStore.
   TrustManagerFactory tmf =
       TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
   tmf.init(mKeyStore);
   return tmf.getTrustManagers();
 }
Example #18
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");
  }
  /**
   * 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());
  }
Example #20
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());
  }
  public RippleTrustManager(KeyStore localKeyStore) {
    try {
      TrustManagerFactory tmf =
          TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
      tmf.init((KeyStore) null);

      defaultTrustManager = findX509TrustManager(tmf);
      if (defaultTrustManager == null) {
        throw new IllegalStateException("not found X509TrustManager");
      }

      localTrustManager = new LocalStoreX509TrustManager(localKeyStore);

      ArrayList<X509Certificate> allIssuers = new ArrayList<X509Certificate>();
      for (X509Certificate cert : defaultTrustManager.getAcceptedIssuers()) {
        allIssuers.add(cert);
      }
      for (X509Certificate cert : localTrustManager.getAcceptedIssuers()) {
        allIssuers.add(cert);
      }
      acceptedIssuers = allIssuers.toArray(new X509Certificate[allIssuers.size()]);
    } catch (GeneralSecurityException e) {
      throw new RuntimeException(e);
    }
  }
 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);
 }
 private X509TrustManager[] initDefaultTrustManagers() {
   try {
     TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509", "SunJSSE");
     tmf.init((KeyStore) null);
     TrustManager[] trustManagers = tmf.getTrustManagers();
     if (trustManagers == null || trustManagers.length == 0) {
       return null;
     }
     List x509TrustManagers = new ArrayList();
     for (int i = 0; i < trustManagers.length; i++) {
       TrustManager trustManager = trustManagers[i];
       if (trustManager instanceof X509TrustManager) {
         x509TrustManagers.add(trustManager);
       }
     }
     return (X509TrustManager[])
         x509TrustManagers.toArray(new X509TrustManager[x509TrustManagers.size()]);
   } catch (NoSuchAlgorithmException e) {
     SVNDebugLog.getDefaultLog().log(SVNLogType.DEFAULT, e, Level.FINEST);
   } catch (NoSuchProviderException e) {
     SVNDebugLog.getDefaultLog().log(SVNLogType.DEFAULT, e, Level.FINEST);
   } catch (KeyStoreException e) {
     SVNDebugLog.getDefaultLog().log(SVNLogType.DEFAULT, e, Level.FINEST);
   }
   return null;
 }
  /**
   * Creates trust managers using the receiver's trust store configuration.
   *
   * @param context context for status messages
   * @return an array of trust managers or {@code null} if no trust store configuration was provided
   * @throws NoSuchProviderException if a provider specified for one of the trust manager components
   *     is not known to the platform
   * @throws NoSuchAlgorithmException if an algorithm specified for one of the trust manager
   *     components is not known to the relevant provider
   * @throws KeyStoreException if an error occurs in reading a key store containing trust anchors
   */
  private TrustManager[] createTrustManagers(ContextAware context)
      throws NoSuchProviderException, NoSuchAlgorithmException, KeyStoreException {

    if (getTrustStore() == null) return null;

    KeyStore trustStore = getTrustStore().createKeyStore();
    context.addInfo(
        "trust store of type '"
            + trustStore.getType()
            + "' provider '"
            + trustStore.getProvider()
            + "': "
            + getTrustStore().getLocation());

    TrustManagerFactory tmf = getTrustManagerFactory().createTrustManagerFactory();
    context.addInfo(
        "trust manager algorithm '"
            + tmf.getAlgorithm()
            + "' provider '"
            + tmf.getProvider()
            + "'");

    tmf.init(trustStore);
    return tmf.getTrustManagers();
  }
Example #25
0
 public MyTrustManager(X509TrustManager localTrustManager)
     throws NoSuchAlgorithmException, KeyStoreException {
   TrustManagerFactory var4 =
       TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
   var4.init((KeyStore) null);
   defaultTrustManager = chooseTrustManager(var4.getTrustManagers());
   this.localTrustManager = localTrustManager;
 }
Example #26
0
 private TrustManager[] getTrustMgrs(final String tsPath, final String tsPassword)
     throws Exception {
   TrustManagerFactory fact =
       TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
   KeyStore ts = loadStore(tsPath, tsPassword);
   fact.init(ts);
   return fact.getTrustManagers();
 }
  public static SSLSocketFactory getSocketFactory(
      String caCrtFile, String crtFile, String keyFile, String password) throws Exception {

    char[] passwordCharArray = password == null ? new char[0] : password.toCharArray();

    Security.addProvider(new BouncyCastleProvider());
    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    X509Certificate caCert =
        (X509Certificate)
            cf.generateCertificate(
                new ByteArrayInputStream(Files.readAllBytes(Paths.get(caCrtFile))));

    X509Certificate cert =
        (X509Certificate)
            cf.generateCertificate(
                new ByteArrayInputStream(Files.readAllBytes(Paths.get(crtFile))));

    File privateKeyFile = new File(keyFile);
    PEMParser pemParser = new PEMParser(new FileReader(privateKeyFile));
    PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build(passwordCharArray);
    JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");

    Object object = pemParser.readObject();
    KeyPair kp;

    if (object instanceof PEMEncryptedKeyPair) {
      kp = converter.getKeyPair(((PEMEncryptedKeyPair) object).decryptKeyPair(decProv));
    } else {
      kp = converter.getKeyPair((PEMKeyPair) object);
    }

    pemParser.close();

    KeyStore caKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    caKeyStore.load(null, null);
    caKeyStore.setCertificateEntry("ca-certificate", caCert);
    TrustManagerFactory trustManagerFactory =
        TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(caKeyStore);

    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(null, null);
    keyStore.setCertificateEntry("certificate", cert);
    keyStore.setKeyEntry(
        "private-key",
        kp.getPrivate(),
        passwordCharArray,
        new java.security.cert.Certificate[] {cert});
    KeyManagerFactory keyManagerFactory =
        KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, passwordCharArray);

    SSLContext context = SSLContext.getInstance("TLSv1");
    context.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

    return context.getSocketFactory();
  }
 public X509Extended7DeployTrustManager()
     throws KeyStoreException, NoSuchAlgorithmException, NoSuchProviderException,
         CertificateException {
   TrustManagerFactory localTrustManagerFactory =
       TrustManagerFactory.getInstance("SunX509", "SunJSSE");
   localTrustManagerFactory.init((KeyStore) null);
   TrustManager[] arrayOfTrustManager = localTrustManagerFactory.getTrustManagers();
   this.trustManager = ((X509ExtendedTrustManager) arrayOfTrustManager[0]);
 }
Example #29
0
 private static X509TrustManager createDefaultTrustManager()
     throws KeyStoreException, NoSuchAlgorithmException {
   String algorithm = TrustManagerFactory.getDefaultAlgorithm();
   TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);
   tmf.init((KeyStore) null);
   TrustManager[] tms = tmf.getTrustManagers();
   X509TrustManager trustManager = findX509TrustManager(tms);
   return trustManager;
 }
 /**
  * Get the TrustManagers for the specified trust store.
  *
  * @param tsFile The trust store file
  * @param tsPass The trust store password
  * @return The TrustManagers that can manager the specified trust store.
  * @throws Exception
  */
 protected TrustManager[] getTrustManagers(String tsFile, String tsPass) throws Exception {
   tsFile = JavaKeyStoreHandler.getTrustStoreName(tsFile);
   tsPass = JavaKeyStoreHandler.getTrustStorePassword(tsPass);
   KeyStore ts = KeyStore.getInstance("JKS");
   ts.load(new FileInputStream(tsFile), tsPass.toCharArray());
   TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
   tmf.init(ts);
   return tmf.getTrustManagers();
 }