Пример #1
0
 private static KeyManager[] getKeyMgrs(
     VertxInternal vertx, final String ksPath, final String ksPassword) throws Exception {
   KeyManagerFactory fact = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
   KeyStore ks = loadStore(vertx, ksPath, ksPassword);
   fact.init(ks, ksPassword != null ? ksPassword.toCharArray() : null);
   return fact.getKeyManagers();
 }
Пример #2
0
  /** Gets the initialized key managers. */
  protected KeyManager[] getKeyManagers(
      String keystoreType, String keystoreProvider, String algorithm, String keyAlias)
      throws Exception {

    KeyManager[] kms = null;

    String keystorePass = getKeystorePassword();

    KeyStore ks = getKeystore(keystoreType, keystoreProvider, keystorePass);
    if (keyAlias != null && !ks.isKeyEntry(keyAlias)) {
      throw new IOException(sm.getString("jsse.alias_no_key_entry", keyAlias));
    }

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
    String keyPass = endpoint.getKeyPass();
    if (keyPass == null) {
      keyPass = keystorePass;
    }
    kmf.init(ks, keyPass.toCharArray());

    kms = kmf.getKeyManagers();
    if (keyAlias != null) {
      String alias = keyAlias;
      if (JSSESocketFactory.defaultKeystoreType.equals(keystoreType)) {
        alias = alias.toLowerCase(Locale.ENGLISH);
      }
      for (int i = 0; i < kms.length; i++) {
        kms[i] = new JSSEKeyManager((X509KeyManager) kms[i], alias);
      }
    }

    return kms;
  }
Пример #3
0
    MyX509KeyManager(File keyStore, char[] password) throws Exception {
      // create a "default" JSSE X509KeyManager.

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

      KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509", "SunJSSE");
      kmf.init(ks, password);

      KeyManager kms[] = kmf.getKeyManagers();

      /*
       * Iterate over the returned keymanagers, look
       * for an instance of X509KeyManager.  If found,
       * use that as our "default" key manager.
       */
      for (int i = 0; i < kms.length; i++) {
        if (kms[i] instanceof X509KeyManager) {
          pkixKeyManager = (X509KeyManager) kms[i];
          return;
        }
      }

      /*
       * Find some other way to initialize, or else we have to fail the
       * constructor.
       */
      throw new Exception("Couldn't initialize");
    }
  /** Gets the initialized key managers. */
  protected KeyManager[] getKeyManagers(String algorithm, String keyAlias) throws Exception {

    KeyManager[] kms = null;

    String keystorePass = getKeystorePassword();

    KeyStore ks = getKeystore(keystorePass);
    if (keyAlias != null && !ks.isKeyEntry(keyAlias)) {
      throw new IOException(sm.getString("jsse.alias_no_key_entry", keyAlias));
    }

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
    kmf.init(ks, keystorePass.toCharArray());

    kms = kmf.getKeyManagers();
    if (keyAlias != null) {
      // START SJSAS 6266949
      /*
      if (JSSESocketFactory.defaultKeystoreType.equals(keystoreType)) {
          keyAlias = keyAlias.toLowerCase();
      }
      */
      // END SJSAS 6266949

      for (int i = 0; i < kms.length; i++) {
        kms[i] = new JSSEKeyManager((X509KeyManager) kms[i], keyAlias);
      }
    }

    return kms;
  }
  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;
    }
  }
Пример #6
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();
  }
Пример #7
0
 public static void main(String[] args) throws Exception {
   Properties properties = new Properties();
   FileInputStream propFile = new FileInputStream("store.properties");
   properties.load(propFile);
   final String id = properties.getProperty("ID");
   final String placeForFiles = properties.getProperty("FilePlace");
   int servicePort = Integer.parseInt(properties.getProperty("ServicePort"));
   int tcpPort = Integer.parseInt(properties.getProperty("TCPPort"));
   String ksName = properties.getProperty("KeyStore");
   KeyStore ks = KeyStore.getInstance(properties.getProperty("KeyStoreType"));
   char[] password = properties.getProperty("Password").toCharArray();
   char[] passwordForKey = properties.getProperty("PasswordForKey").toCharArray();
   ks.load(new FileInputStream(ksName), password);
   KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
   kmf.init(ks, passwordForKey);
   SSLContext context = SSLContext.getInstance("TLS");
   context.init(kmf.getKeyManagers(), null, null);
   SSLServerSocketFactory ssf = context.getServerSocketFactory();
   SSLServerSocket serverSocket = (SSLServerSocket) ssf.createServerSocket(tcpPort);
   ServiceThread serviceThread = new ServiceThread(servicePort, id);
   serviceThread.start();
   while (!serverSocket.isClosed()) {
     ClientThread client = new ClientThread(placeForFiles);
     SSLSocket socket = (SSLSocket) serverSocket.accept();
     socket.startHandshake();
     client.setSocket(socket);
     client.start();
   }
 }
Пример #8
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;
  }
Пример #9
0
 private KeyManager[] getKeyManagers(InputStream certificate, String passphrase)
     throws IOException {
   if (key_managers == null) {
     KeyStore ks;
     try {
       ks = KeyStore.getInstance("PKCS12");
     } catch (KeyStoreException e) {
       throw new RuntimeException("Unable to create key store.");
     }
     char certphrase[] = passphrase.toCharArray();
     try {
       ks.load(certificate, certphrase);
     } catch (GeneralSecurityException e) {
       throw new RuntimeException("Bad certificate or unknown type.");
     } finally {
       closeQuietly(certificate);
     }
     KeyManagerFactory kmf;
     try {
       kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
       kmf.init(ks, certphrase);
     } catch (GeneralSecurityException e) {
       throw new RuntimeException(e.getMessage());
     }
     key_managers = kmf.getKeyManagers();
   }
   return key_managers;
 }
  /**
   * @return
   * @throws NoSuchAlgorithmException
   * @throws KeyStoreException
   * @throws UnrecoverableKeyException
   * @throws IOException
   * @throws CertificateException
   */
  private KeyManager[] initKeyManagers()
      throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, IOException,
          CertificateException {
    // Initialize trust manager factory and set trusted CA list using keystore
    if (StringUtils.isEmpty(this.keyStorePath)) {
      log.info("Unset [keyStorePath] parameter, disable local private and certificate.");
      return null;
    } else {
      log.info(
          String.format("Loading private key and certificate from store: [%s]", this.keyStorePath));
      // Load key store
      KeyStore keystore = KeyStore.getInstance("JKS");
      InputStream in = Helper.getResourceAsStream(this.getClass(), this.keyStorePath);
      if (in == null) {
        throw new IOException(
            String.format("Could not reading from : [%s]", this.trustCertsStorePath));
      }
      keystore.load(in, this.keyStorePassword);

      KeyManagerFactory kmf = KeyManagerFactory.getInstance(this.getKeyManagerAlgorithm());
      kmf.init(keystore, this.keyStoreKeyPassword);
      log.info(String.format("Initialized key store: [%s]", this.keyStorePath));

      KeyManager[] keyManagers = kmf.getKeyManagers();
      return keyManagers;
    }
  }
Пример #11
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!");
  }
Пример #12
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);
   }
 }
Пример #13
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;
  }
 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;
 }
Пример #15
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;
  }
Пример #16
0
  /** Loads a keystore from a base64-encoded String. Returns the KeyManager[] for the result. */
  private KeyManager[] getKeyManagers(KeyStore keyStore) throws Exception {
    String algorithm = KeyManagerFactory.getDefaultAlgorithm();
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(algorithm);
    keyManagerFactory.init(keyStore, PASSWORD.toCharArray());

    return keyManagerFactory.getKeyManagers();
  }
Пример #17
0
  static {
    String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
    if (algorithm == null) {
      algorithm = "SunX509";
    }

    SSLContext serverContext;
    SSLContext clientContext;
    try {
      KeyStore ks = KeyStore.getInstance("JKS");
      ks.load(BogusKeyStore.asInputStream(), BogusKeyStore.getKeyStorePassword());

      // Set up key manager factory to use our key store
      KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
      kmf.init(ks, BogusKeyStore.getCertificatePassword());

      // Initialize the SSLContext to work with our key managers.
      serverContext = SSLContext.getInstance(PROTOCOL);
      serverContext.init(kmf.getKeyManagers(), null, null);
    } catch (Exception e) {
      throw new Error("Failed to initialize the server-side SSLContext", e);
    }

    try {
      clientContext = SSLContext.getInstance(PROTOCOL);
      clientContext.init(null, BogusTrustManagerFactory.getTrustManagers(), null);
    } catch (Exception e) {
      throw new Error("Failed to initialize the client-side SSLContext", e);
    }

    SERVER_CONTEXT = serverContext;
    CLIENT_CONTEXT = clientContext;
  }
Пример #18
0
  /**
   * Used to get the base ssl context in which to create the server socket. This is basically just
   * so we can have a custom location for key stores.
   */
  public SSLContext getSSLContext(String keyStoreName, String password) throws IOException {
    try {
      // Check the key manager factory
      KeyManagerFactory kmf = KeyManagerFactory.getInstance(this.keyManagerType);

      File ksFile = new File(keyStoreName);
      if (!ksFile.exists() || !ksFile.isFile())
        throw new WinstoneException(
            SSL_RESOURCES.getString("HttpsListener.KeyStoreNotFound", ksFile.getPath()));
      InputStream in = new FileInputStream(ksFile);
      char[] passwordChars = password == null ? null : password.toCharArray();
      KeyStore ks = KeyStore.getInstance("JKS");
      ks.load(in, passwordChars);
      kmf.init(ks, passwordChars);
      Logger.log(Logger.FULL_DEBUG, SSL_RESOURCES, "HttpsListener.KeyCount", ks.size() + "");
      for (Enumeration e = ks.aliases(); e.hasMoreElements(); ) {
        String alias = (String) e.nextElement();
        Logger.log(
            Logger.FULL_DEBUG,
            SSL_RESOURCES,
            "HttpsListener.KeyFound",
            new String[] {alias, ks.getCertificate(alias) + ""});
      }

      SSLContext context = SSLContext.getInstance("SSL");
      context.init(kmf.getKeyManagers(), null, null);
      Arrays.fill(passwordChars, 'x');
      return context;
    } catch (IOException err) {
      throw err;
    } catch (Throwable err) {
      throw new WinstoneException(
          SSL_RESOURCES.getString("HttpsListener.ErrorGettingContext"), err);
    }
  }
Пример #19
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);
    }
  }
  private static SSLContext createBougusServerSslContext()
      throws GeneralSecurityException, IOException {
    // Create keystore
    KeyStore ks = KeyStore.getInstance("JKS");
    InputStream in = null;
    try {
      in = BogusSslContextFactory.class.getResourceAsStream(BOGUS_KEYSTORE);
      ks.load(in, BOGUS_PW);
    } finally {
      if (in != null) {
        try {
          in.close();
        } catch (IOException ignored) {
        }
      }
    }

    // Set up key manager factory to use our key store
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KEY_MANAGER_FACTORY_ALGORITHM);
    kmf.init(ks, BOGUS_PW);

    // Initialize the SSLContext to work with our key managers.
    SSLContext sslContext = SSLContext.getInstance(PROTOCOL);
    sslContext.init(kmf.getKeyManagers(), BogusTrustManagerFactory.X509_MANAGERS, null);

    return sslContext;
  }
Пример #21
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 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);
 }
Пример #23
0
  /** 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());
    }
  }
  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();
  }
Пример #25
0
 /** @return key managers loaded for this service. */
 public synchronized KeyManager[] getKeyManagers() throws GeneralSecurityException {
   if (mKeyStore == null) {
     throw new NullPointerException("null mKeyStore");
   }
   KeyManagerFactory factory =
       KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
   factory.init(mKeyStore, "".toCharArray());
   return factory.getKeyManagers();
 }
Пример #26
0
 private SSLSocketFactory createSocketFactory(String domain) throws Exception {
   SSLSocketFactory factory;
   KeyManagerFactory keyManagerFactory = getKeyManagerFactory(keystore, KEYSTORE_PASSWORD);
   SSLContext sslContext = SSLContext.getInstance("TLS");
   KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();
   keyManagers = wrapKeyManagers(keyManagers, domain);
   sslContext.init(keyManagers, getAllTrustingManager(), secureRandom);
   factory = sslContext.getSocketFactory();
   return factory;
 }
Пример #27
0
  public KeyManagerFactory getKeyManagerFactory(KeyStore keystore, String password)
      throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException,
          UnrecoverableKeyException {
    char[] passphrase = password == null ? null : password.toCharArray();
    KeyManagerFactory keyManagerFactory =
        KeyManagerFactory.getInstance(Configuration.getSSLAlgorithm());

    keyManagerFactory.init(keystore, passphrase);
    return keyManagerFactory;
  }
 private static KeyManager[] createKeyManagers(final KeyStore keystore, final String password)
     throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
   if (keystore == null) {
     throw new IllegalArgumentException("Keystore may not be null");
   }
   KeyManagerFactory kmfactory =
       KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
   kmfactory.init(keystore, password != null ? password.toCharArray() : null);
   return kmfactory.getKeyManagers();
 }
Пример #29
0
  private KeyManager[] createKeyManagers(KeyStore keystore)
      throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
    bombIfNull(keystore, "Keystore may not be null");

    LOG.trace("Initializing key manager");
    KeyManagerFactory kmfactory =
        KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmfactory.init(keystore, keystorePassword.toCharArray());
    return kmfactory.getKeyManagers();
  }
Пример #30
0
  public static SSLContext getFakeSSLContext(String host, String port) throws Exception {
    SSLContext sslContext = SSLContext.getInstance("TLS");
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");

    kmf.init(
        SslCertificateHelper.getClientKeyStore(host), SslCertificateHelper.KS_PASS.toCharArray());
    sslContext.init(kmf.getKeyManagers(), null, null);
    // sslparams.s
    // param.setSSLParameters(sslparams);
    return sslContext;
  }