Esempio n. 1
1
  public static SSLContext createSSLContext(
      boolean clientMode, String keystore, String password, String trustStore, String trustPassword)
      throws Exception {
    // Create/initialize the SSLContext with key material
    char[] passphrase = password.toCharArray();
    // First initialize the key and trust material.
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(new FileInputStream(keystore), passphrase);
    SSLContext sslContext = SSLContext.getInstance("TLS");

    if (clientMode) {
      // TrustManager's decide whether to allow connections.
      TrustManagerFactory tmf =
          TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
      tmf.init(ks);
      sslContext.init(null, tmf.getTrustManagers(), null);

    } else {
      // KeyManager's decide which key material to use.
      KeyManagerFactory kmf =
          KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
      kmf.init(ks, passphrase);

      if (trustStore != null) {
        KeyStore ts = KeyStore.getInstance("JKS");
        ts.load(new FileInputStream(trustStore), trustPassword.toCharArray());
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
        tmf.init(ts);
        System.out.println("Using the trust store for client auth");
        sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
      } else sslContext.init(kmf.getKeyManagers(), null, null);
    }
    return sslContext;
  }
    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");
    }
Esempio n. 3
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;
  }
  protected CamelContext createPropertiesPlaceholderAwareContext() throws Exception {
    Properties supplementalProperties = new Properties();

    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    TrustManagerFactory tmf =
        TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    SecureRandom sr = null;
    try {
      sr = SecureRandom.getInstance("SHA1PRNG");
    } catch (NoSuchAlgorithmException e) {
      // Ignore
    }

    SSLContext sslc = SSLContext.getInstance("TLS");
    sslc.init(null, null, null);
    SSLSocket socket = (SSLSocket) sslc.getSocketFactory().createSocket();

    supplementalProperties.setProperty("keyStoreParameters.type", KeyStore.getDefaultType());
    supplementalProperties.setProperty("keyStoreParameters.provider", ks.getProvider().getName());

    supplementalProperties.setProperty(
        "keyManagersParameters.algorithm", KeyManagerFactory.getDefaultAlgorithm());
    supplementalProperties.setProperty(
        "keyManagersParameters.provider", kmf.getProvider().getName());

    supplementalProperties.setProperty(
        "trustManagersParameters.algorithm", TrustManagerFactory.getDefaultAlgorithm());
    supplementalProperties.setProperty(
        "trustManagersParameters.provider", tmf.getProvider().getName());

    if (sr != null) {
      supplementalProperties.setProperty("secureRandomParameters.algorithm", "SHA1PRNG");
      supplementalProperties.setProperty(
          "secureRandomParameters.provider", sr.getProvider().getName());
    }

    supplementalProperties.setProperty(
        "sslContextParameters.provider", sslc.getProvider().getName());
    supplementalProperties.setProperty("cipherSuite.0", socket.getSupportedCipherSuites()[0]);

    // Have to skip this guy because he doesn't work with TLS as the SSLContext protocol
    String ssp = "";
    for (String protocol : socket.getSupportedProtocols()) {
      if (!"SSLv2Hello".equals(protocol)) {
        ssp = protocol;
        break;
      }
    }
    supplementalProperties.setProperty("secureSocketProtocol.0", ssp);

    return this.createPropertiesPlaceholderAwareContext(supplementalProperties);
  }
 private synchronized void resetKeyStoreTrustManager() throws GeneralSecurityException {
   TrustManagerFactory factory =
       TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
   factory.init(keyStore);
   TrustManager[] trustManagers = factory.getTrustManagers();
   for (TrustManager tm : trustManagers)
     if (tm instanceof X509TrustManager) {
       setKeyStoreTrustManager((X509TrustManager) tm);
       return;
     }
   throw new KeyStoreException(
       TrustManagerFactory.getDefaultAlgorithm() + " trust manager not supported");
 }
Esempio n. 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;
  }
  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);
    }
  }
  /** 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());
    }
  }
Esempio n. 9
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");
  }
Esempio n. 10
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();
 }
 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;
 }
Esempio n. 12
0
  /** 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 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;
    }
  }
Esempio n. 14
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;
  }
  /**
   * 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());
  }
  /**
   * 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;
    }
  }
Esempio n. 17
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;
 }
Esempio n. 18
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();
  }
  // START SJSAS 6439313
  public void init() throws IOException {
    // END SJSAS 6439313
    try {

      String clientAuthStr = (String) attributes.get("clientauth");
      if (clientAuthStr != null) {
        clientAuth = Boolean.valueOf(clientAuthStr).booleanValue();
      }

      // SSL protocol variant (e.g., TLS, SSL v3, etc.)
      String protocol = (String) attributes.get("protocol");
      if (protocol == null) {
        protocol = defaultProtocol;
      }

      // Certificate encoding algorithm (e.g., SunX509)
      String algorithm = (String) attributes.get("algorithm");
      if (algorithm == null) {
        algorithm = defaultAlgorithm;
      }

      // Create and init SSLContext
      /* SJSAS 6439313
      SSLContext context = SSLContext.getInstance(protocol);
       */

      // START SJSAS 6439313
      context = SSLContext.getInstance(protocol);
      // END SJSAS 6439313

      // Configure SSL session timeout and cache size
      configureSSLSessionContext(context.getServerSessionContext());

      String trustAlgorithm = (String) attributes.get("truststoreAlgorithm");
      if (trustAlgorithm == null) {
        trustAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
      }

      context.init(
          getKeyManagers(algorithm, (String) attributes.get("keyAlias")),
          getTrustManagers(trustAlgorithm),
          new SecureRandom());

      // create proxy
      sslProxy = context.getServerSocketFactory();

      // Determine which cipher suites to enable
      String requestedCiphers = (String) attributes.get("ciphers");
      if (requestedCiphers != null) {
        enabledCiphers = getEnabledCiphers(requestedCiphers, sslProxy.getSupportedCipherSuites());
      }

    } catch (Exception e) {
      if (e instanceof IOException) throw (IOException) e;
      throw new IOException(e.getMessage());
    }
  }
Esempio n. 21
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;
 }
 private static TrustManager[] createTrustManagers(final KeyStore keystore)
     throws KeyStoreException, NoSuchAlgorithmException {
   if (keystore == null) {
     throw new IllegalArgumentException("Keystore may not be null");
   }
   TrustManagerFactory tmfactory =
       TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
   tmfactory.init(keystore);
   return tmfactory.getTrustManagers();
 }
 /** Constructor for EasyX509TrustManager. */
 public HighSecurityX509TrustManager(KeyStore keystore)
     throws NoSuchAlgorithmException, KeyStoreException {
   super();
   TrustManagerFactory factory =
       TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
   factory.init(keystore);
   TrustManager[] trustmanagers = factory.getTrustManagers();
   if (trustmanagers.length == 0) {
     throw new NoSuchAlgorithmException("no trust manager found");
   }
   this.standardTrustManager = (X509TrustManager) trustmanagers[0];
 }
 /**
  * This attempts to load the TrustManagers from the supplied <code>
  * InputStream</code> using the supplied password.
  *
  * @param is <code>InputStream</code> containing the truststore
  * @param password <code>String</code> to unlock the truststore
  * @param storeType <code>String</code> of truststore
  * @return <code>TrustManager[]</code>
  * @throws IOException if the keystore cannot be loaded
  * @throws GeneralSecurityException if an errors occurs while loading the TrustManagers
  */
 private TrustManager[] initTrustManager(
     final InputStream is, final String password, final String storeType)
     throws IOException, GeneralSecurityException {
   TrustManager[] tm = null;
   if (is != null) {
     final TrustManagerFactory tmf =
         TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
     tmf.init(this.loadKeyStore(is, password, storeType));
     tm = tmf.getTrustManagers();
   }
   return tm;
 }
Esempio n. 25
0
 private X509TrustManager getX509TrustManager(final KeyStore trustStore)
     throws GeneralSecurityException, IOException {
   TrustManagerFactory trustManagerFactory =
       TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
   trustManagerFactory.init(trustStore);
   for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) {
     if (trustManager instanceof X509TrustManager) {
       return (X509TrustManager) trustManager;
     }
   }
   return null;
 }
  /*
   * In case of self signed certificates on Server. Two things needs to be taken care
   *  1)Authenticate to the HTTPS server using a private key.
   *  2)Validate the identity of the HTTPS server against a list of trusted certificates
   *
   * Ref - http://developer.android.com/reference/org/apache/http/conn/ssl/SSLSocketFactory.html
   */
  private static SSLContext createEasySSLContext() throws IOException {
    try {

      // Client should authenticate itself with the valid certificate to Server.
      InputStream clientStream =
          VolleySampleApplication.getContext()
              .getResources()
              .openRawResource(R.raw.production_test_client);
      char[] password = "******".toCharArray();

      KeyStore keyStore = KeyStore.getInstance("PKCS12");
      keyStore.load(clientStream, password);

      KeyManagerFactory keyManagerFactory =
          KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
      keyManagerFactory.init(keyStore, password);

      // Client should also add the CA certificate obtained from server and create TrustManager from
      // it for the client to validate the
      // identity of the server.
      KeyStore trustStore = KeyStore.getInstance("BKS");
      InputStream instream = null;
      instream =
          VolleySampleApplication.getContext()
              .getResources()
              .openRawResource(R.raw.production_test_ca);

      try {
        trustStore.load(instream, "XXXXXXXX".toCharArray());
      } catch (Exception e) {
        e.printStackTrace();
      } finally {
        try {
          instream.close();
        } catch (Exception ignore) {
        }
      }

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

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

      return context;
    } catch (Exception e) {
      e.printStackTrace();
      throw new IOException(e.getMessage());
    }
  }
    private String downloadUrl(String urlString)
        throws IOException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException,
            CertificateException {

      HostnameVerifier hostnameVerifier =
          new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
              HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
              return hv.verify("localhost", session);
            }
          };
      URL url = new URL(urlString);
      HttpsURLConnection conn = null;
      // Get an instance of the Bouncy Castle KeyStore format
      KeyStore trusted = KeyStore.getInstance("BKS");
      // Get the raw resource, which contains the keystore with
      // your trusted certificates (root and any intermediate certs)
      InputStream in =
          activity.getApplicationContext().getResources().openRawResource(R.raw.mykeystore);
      try {
        // Initialize the keystore with the provided trusted
        // certificates
        // Also provide the password of the keystore
        trusted.load(in, "my_password".toCharArray());
      } finally {
        in.close();
      }
      String algorithm = TrustManagerFactory.getDefaultAlgorithm();
      TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);
      tmf.init(trusted);

      SSLContext context = SSLContext.getInstance("TLS");
      context.init(null, tmf.getTrustManagers(), null);

      conn = (HttpsURLConnection) url.openConnection();
      conn.setHostnameVerifier(hostnameVerifier);
      conn.setSSLSocketFactory(context.getSocketFactory());
      conn.setReadTimeout(10000 /* milliseconds */);
      conn.setConnectTimeout(15000 /* milliseconds */);
      conn.setRequestMethod("GET");
      conn.setDoInput(true);
      conn.setRequestProperty("Accept", "text/xml");
      conn.setRequestProperty(
          "Authorization",
          "Basic "
              + Base64.encodeToString(
                  ((this.userName + ":" + this.passWord).getBytes()), Base64.NO_WRAP));
      // Starts the query
      conn.connect();
      return conn.getResponseMessage();
    }
Esempio n. 28
0
 public eg(KeyStore keystore) throws NoSuchAlgorithmException, KeyStoreException {
   a = null;
   TrustManagerFactory trustmanagerfactory =
       TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
   trustmanagerfactory.init(keystore);
   keystore = trustmanagerfactory.getTrustManagers();
   if (keystore.length == 0) {
     throw new NoSuchAlgorithmException("no trust manager found");
   } else {
     a = (X509TrustManager) keystore[0];
     return;
   }
 }
  private static TrustManager[] createTrustManagers() throws GeneralSecurityException, IOException {
    InputStream keyStoreStream =
        Thread.currentThread().getContextClassLoader().getResourceAsStream("ssltest-keystore.jks");
    char[] keyStorePassword = "******".toCharArray();
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(keyStoreStream, keyStorePassword);
    assert (ks.size() > 0);

    TrustManagerFactory tmf =
        TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(ks);
    return tmf.getTrustManagers();
  }
 private static X509TrustManager getDefaultTrustManager() {
   try {
     TrustManagerFactory tmf =
         TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
     tmf.init((KeyStore) null);
     for (TrustManager trustManager : tmf.getTrustManagers()) {
       if (trustManager instanceof X509TrustManager) return (X509TrustManager) trustManager;
     }
   } catch (NoSuchAlgorithmException | KeyStoreException e) {
     throw new RuntimeException("X.509 not supported.", e);
   }
   return null;
 }