Example #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;
  }
    private SSLSocketFactory newSslSocketFactory() {
      try {
        // 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 =
            context.getResources().openRawResource(tracker.springversion1.R.raw.mykeystore);

        try {
          // Initialize the keystore with the provided trusted
          // certificates
          // Also provide the password of the keystore
          trusted.load(in, "mysecret".toCharArray());
        } finally {
          in.close();
        }
        // Pass the keystore to the SSLSocketFactory. The factory is
        // responsible
        // for the verification of the server certificate.
        SSLSocketFactory sf = new SSLSocketFactory(trusted);
        // Hostname verification from certificate
        // http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d4e506
        sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
        //				 ALLOW_ALL_HOSTNAME_VERIFIER
        return sf;
      } catch (Exception e) {
        throw new AssertionError(e);
      }
    }
Example #3
0
  static {
    String algorithm = JiveGlobals.getProperty("xmpp.socket.ssl.algorithm", "TLS");
    String storeType = JiveGlobals.getProperty("xmpp.socket.ssl.storeType", "jks");

    // Get the keystore location. The default location is security/keystore
    keyStoreLocation =
        JiveGlobals.getProperty(
            "xmpp.socket.ssl.keystore",
            "resources" + File.separator + "security" + File.separator + "keystore");
    keyStoreLocation = JiveGlobals.getHomeDirectory() + File.separator + keyStoreLocation;

    // Get the keystore password. The default password is "changeit".
    keypass = JiveGlobals.getProperty("xmpp.socket.ssl.keypass", "changeit");
    keypass = keypass.trim();

    // Get the truststore location; default at security/truststore
    trustStoreLocation =
        JiveGlobals.getProperty(
            "xmpp.socket.ssl.truststore",
            "resources" + File.separator + "security" + File.separator + "truststore");
    trustStoreLocation = JiveGlobals.getHomeDirectory() + File.separator + trustStoreLocation;

    // Get the truststore passwprd; default is "changeit".
    trustpass = JiveGlobals.getProperty("xmpp.socket.ssl.trustpass", "changeit");
    trustpass = trustpass.trim();

    try {
      keyStore = KeyStore.getInstance(storeType);
      keyStore.load(new FileInputStream(keyStoreLocation), keypass.toCharArray());

      trustStore = KeyStore.getInstance(storeType);
      trustStore.load(new FileInputStream(trustStoreLocation), trustpass.toCharArray());

      sslFactory =
          (SSLJiveServerSocketFactory)
              SSLJiveServerSocketFactory.getInstance(algorithm, keyStore, trustStore);
    } catch (Exception e) {
      Log.error(
          "SSLConfig startup problem.\n"
              + "  storeType: ["
              + storeType
              + "]\n"
              + "  keyStoreLocation: ["
              + keyStoreLocation
              + "]\n"
              + "  keypass: ["
              + keypass
              + "]\n"
              + "  trustStoreLocation: ["
              + trustStoreLocation
              + "]\n"
              + "  trustpass: ["
              + trustpass
              + "]",
          e);
      keyStore = null;
      trustStore = null;
      sslFactory = null;
    }
  }
 public final void afterPropertiesSet() throws GeneralSecurityException, IOException {
   if (StringUtils.hasLength(provider) && StringUtils.hasLength(type)) {
     keyStore = KeyStore.getInstance(type, provider);
   } else if (StringUtils.hasLength(type)) {
     keyStore = KeyStore.getInstance(type);
   } else {
     keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
   }
   InputStream is = null;
   try {
     if (location != null && location.exists()) {
       is = location.getInputStream();
       if (logger.isInfoEnabled()) {
         logger.info("Loading key store from " + location);
       }
     } else if (logger.isWarnEnabled()) {
       logger.warn("Creating empty key store");
     }
     keyStore.load(is, password);
   } finally {
     if (is != null) {
       is.close();
     }
   }
 }
  /** {@inheritDoc} */
  public void createKeyStore(char[] store_password) throws KeyStoreException, IOException {
    try {
      KeyStore store;
      if (null == keystore_provider) {
        store = KeyStore.getInstance(keystore_type);
      } else {
        store = KeyStore.getInstance(keystore_type, keystore_provider);
      }

      store.load(null, store_password);

      saveKeyStore(store, store_password);
    } catch (NoSuchProviderException failed) {
      KeyStoreException failure =
          new KeyStoreException("NoSuchProviderException during keystore processing");
      failure.initCause(failed);
      throw failure;
    } catch (NoSuchAlgorithmException failed) {
      KeyStoreException failure =
          new KeyStoreException("NoSuchAlgorithmException during keystore processing");
      failure.initCause(failed);
      throw failure;
    } catch (CertificateException failed) {
      KeyStoreException failure =
          new KeyStoreException("CertificateException during keystore processing");
      failure.initCause(failed);
      throw failure;
    }
  }
Example #6
0
  private SSLContext createSSLContext(final SSLContextService service)
      throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException,
          KeyManagementException, UnrecoverableKeyException {
    SSLContextBuilder builder = SSLContexts.custom();
    final String trustFilename = service.getTrustStoreFile();
    if (trustFilename != null) {
      final KeyStore truststore = KeyStore.getInstance(service.getTrustStoreType());
      try (final InputStream in = new FileInputStream(new File(service.getTrustStoreFile()))) {
        truststore.load(in, service.getTrustStorePassword().toCharArray());
      }
      builder = builder.loadTrustMaterial(truststore, new TrustSelfSignedStrategy());
    }

    final String keyFilename = service.getKeyStoreFile();
    if (keyFilename != null) {
      final KeyStore keystore = KeyStore.getInstance(service.getKeyStoreType());
      try (final InputStream in = new FileInputStream(new File(service.getKeyStoreFile()))) {
        keystore.load(in, service.getKeyStorePassword().toCharArray());
      }
      builder = builder.loadKeyMaterial(keystore, service.getKeyStorePassword().toCharArray());
    }

    SSLContext sslContext = builder.build();
    return sslContext;
  }
Example #7
0
  public static void createPublicCert(
      String targetKeystoreFile,
      String keyName,
      String rootKeystorePath,
      char[] rootKeystorePassword,
      char[] truststorePassword)
      throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException {
    KeyStore signerKeystore = KeyStore.getInstance(keystoreType);
    char[] signerPasswordArray = rootKeystorePassword;
    FileInputStream rootKeystoreInputStream = null;
    try {
      rootKeystoreInputStream = new FileInputStream(rootKeystorePath);
      signerKeystore.load(rootKeystoreInputStream, signerPasswordArray);
    } finally {
      if (rootKeystoreInputStream != null) {
        rootKeystoreInputStream.close();
      }
    }
    Certificate rootCert = findCert(signerKeystore);

    KeyStore keystore = KeyStore.getInstance(keystoreType);
    keystore.load(null, null);
    keystore.setCertificateEntry(keyName + "Cert", rootCert);
    FileOutputStream targetKeystoreOutputStream = null;
    try {
      targetKeystoreOutputStream = new FileOutputStream(targetKeystoreFile);
      keystore.store(targetKeystoreOutputStream, truststorePassword);
    } finally {
      if (targetKeystoreOutputStream != null) {
        targetKeystoreOutputStream.close();
      }
    }
  }
 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);
 }
Example #9
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);
   }
 }
  /** Loads the system trust store. */
  private static KeyStore loadSystemTrustStore()
      throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {

    KeyStore ks;

    if (Build.VERSION.SDK_INT >= 14) {
      ks = KeyStore.getInstance("AndroidCAStore");
      ks.load(null, null);
    } else {
      ks = KeyStore.getInstance("BKS");
      String path = System.getProperty("javax.net.ssl.trustStore");
      if (path == null)
        path =
            System.getProperty("java.home")
                + File.separator
                + "etc"
                + File.separator
                + "security"
                + File.separator
                + "cacerts.bks";
      ks.load(new FileInputStream(path), null);
    }

    return ks;
  }
  /** 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());
    }
  }
  private static KeyStore loadKeyStore() throws GeneralSecurityException {
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    boolean isKeyStoreInitialized = false;
    InputStream in = null;
    try {
      in = new FileInputStream(LC.mailboxd_keystore.value());
      try {
        keyStore.load(in, LC.mailboxd_keystore_password.value().toCharArray());
        isKeyStoreInitialized = true;
      } catch (CertificateException x) {
        ZimbraLog.security.warn("failed to load certificates", x);
      } catch (IOException x) {
        ZimbraLog.security.warn("failed to read keystore file", x);
      }
    } catch (FileNotFoundException x) {
      ZimbraLog.security.info("keystore not present");
    } finally {
      if (in != null)
        try {
          in.close();
        } catch (IOException x) {
          ZimbraLog.security.warn("keystore file can't be closed after reading", x);
        }
    }

    if (!isKeyStoreInitialized) {
      try {
        in = new FileInputStream(LC.mailboxd_keystore_base.value());
        try {
          keyStore.load(in, LC.mailboxd_keystore_base_password.value().toCharArray());
          isKeyStoreInitialized = true;
        } catch (CertificateException x) {
          ZimbraLog.security.warn("failed to load backup certificates", x);
        } catch (IOException x) {
          ZimbraLog.security.warn("failed to read backup keystore file", x);
        }
      } catch (FileNotFoundException x) {
        ZimbraLog.security.warn("backup keystore not found");
      } finally {
        if (in != null)
          try {
            in.close();
          } catch (IOException x) {
            ZimbraLog.security.warn("backup keystore file can't be closed after reading", x);
          }
      }
    }

    if (!isKeyStoreInitialized) {
      keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
      try {
        keyStore.load(null, new char[0]);
      } catch (IOException x) {
        throw new KeyStoreException(x);
      }
    }

    return keyStore;
  }
  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();
  }
Example #14
0
 private KeyStore createKeyStore(@Nullable String path)
     throws IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException {
   String keyStoreType = KeyStore.getDefaultType();
   char[] defaultPassword = "******".toCharArray();
   if (path != null) {
     // If the user provided path, only try to load the keystore at that path.
     KeyStore keyStore = KeyStore.getInstance(keyStoreType);
     FileInputStream is = new FileInputStream(path);
     keyStore.load(is, defaultPassword);
     return keyStore;
   }
   try {
     // Check if we are on Android.
     Class version = Class.forName("android.os.Build$VERSION");
     // Build.VERSION_CODES.ICE_CREAM_SANDWICH is 14.
     if (version.getDeclaredField("SDK_INT").getInt(version) >= 14) {
       // After ICS, Android provided this nice method for loading the keystore,
       // so we don't have to specify the location explicitly.
       KeyStore keystore = KeyStore.getInstance("AndroidCAStore");
       keystore.load(null, null);
       return keystore;
     } else {
       keyStoreType = "BKS";
       path =
           System.getProperty("java.home")
               + "/etc/security/cacerts.bks".replace('/', File.separatorChar);
     }
   } catch (ClassNotFoundException e) {
     // NOP. android.os.Build is not present, so we are not on Android. Fall through.
   } catch (NoSuchFieldException e) {
     throw new RuntimeException(e); // Should never happen.
   } catch (IllegalAccessException e) {
     throw new RuntimeException(e); // Should never happen.
   }
   if (path == null) {
     path = System.getProperty("javax.net.ssl.trustStore");
   }
   if (path == null) {
     // Try this default system location for Linux/Windows/OSX.
     path =
         System.getProperty("java.home")
             + "/lib/security/cacerts".replace('/', File.separatorChar);
   }
   try {
     KeyStore keyStore = KeyStore.getInstance(keyStoreType);
     FileInputStream is = new FileInputStream(path);
     keyStore.load(is, defaultPassword);
     return keyStore;
   } catch (FileNotFoundException e) {
     // If we failed to find a system trust store, load our own fallback trust store. This can fail
     // on Android
     // but we should never reach it there.
     KeyStore keyStore = KeyStore.getInstance("JKS");
     InputStream is = getClass().getResourceAsStream("cacerts");
     keyStore.load(is, defaultPassword);
     return keyStore;
   }
 }
  public static void main(String[] args) throws Exception {
    if (args.length < 1) {
      System.err.println("usage: java PKCS12Import {pkcs12file} [newjksfile]");
      System.exit(1);
    }

    File fileIn = new File(args[0]);
    File fileOut;
    if (args.length > 1) {
      fileOut = new File(args[1]);
    } else {
      fileOut = new File("newstore.jks");
    }

    if (!fileIn.canRead()) {
      System.err.println("Unable to access input keystore: " + fileIn.getPath());
      System.exit(2);
    }

    if (fileOut.exists() && !fileOut.canWrite()) {
      System.err.println("Output file is not writable: " + fileOut.getPath());
      System.exit(2);
    }

    KeyStore kspkcs12 = KeyStore.getInstance("pkcs12");
    KeyStore ksjks = KeyStore.getInstance("jks");

    LineNumberReader in = new LineNumberReader(new InputStreamReader(System.in));
    System.out.print("Enter input keystore passphrase: ");
    char[] inphrase = in.readLine().toCharArray();
    System.out.print("Enter output keystore passphrase: ");
    char[] outphrase = in.readLine().toCharArray();

    kspkcs12.load(new FileInputStream(fileIn), inphrase);

    ksjks.load((fileOut.exists()) ? new FileInputStream(fileOut) : null, outphrase);

    Enumeration eAliases = kspkcs12.aliases();
    int n = 0;
    while (eAliases.hasMoreElements()) {
      String strAlias = (String) eAliases.nextElement();
      System.err.println("Alias " + n++ + ": " + strAlias);

      if (kspkcs12.isKeyEntry(strAlias)) {
        System.err.println("Adding key for alias " + strAlias);
        Key key = kspkcs12.getKey(strAlias, inphrase);

        Certificate[] chain = kspkcs12.getCertificateChain(strAlias);

        ksjks.setKeyEntry(strAlias, key, outphrase, chain);
      }
    }

    OutputStream out = new FileOutputStream(fileOut);
    ksjks.store(out, outphrase);
    out.close();
  }
Example #16
0
  public void configureService(
      String address,
      String pksFilename,
      String pksPassword,
      String trustPksFilename,
      String trustPksPassword)
      throws Exception {
    if (pksFilename != null
        && pksPassword != null
        && trustPksFilename != null
        && trustPksPassword != null) {
      System.setProperty("javax.net.ssl.keyStore", pksFilename);
      System.setProperty("javax.net.ssl.keyStorePassword", pksPassword);
      System.setProperty("javax.net.ssl.trustStore", trustPksFilename);
      System.setProperty("javax.net.ssl.trustStorePassword", trustPksPassword);
    }
    URL wsdlUrl = new URL(address + "?wsdl");
    IoTaService service = new IoTaService(wsdlUrl);
    port = service.getPort(IoTaServicePortType.class);

    // turn off chunked transfer encoding
    Client client = ClientProxy.getClient(port);
    HTTPConduit httpConduit = (HTTPConduit) client.getConduit();
    HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
    httpClientPolicy.setAllowChunking(false);
    httpConduit.setClient(httpClientPolicy);

    if (pksFilename != null) {
      log.debug("Authenticating with certificate in file: " + pksFilename);

      if (!wsdlUrl.getProtocol().equalsIgnoreCase("https")) {
        throw new Exception("Authentication method requires the use of HTTPS");
      }

      KeyStore keyStore = KeyStore.getInstance(pksFilename.endsWith(".p12") ? "PKCS12" : "JKS");
      keyStore.load(new FileInputStream(new File(pksFilename)), pksPassword.toCharArray());
      KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
      keyManagerFactory.init(keyStore, pksPassword.toCharArray());

      KeyStore trustStore =
          KeyStore.getInstance(trustPksFilename.endsWith(".p12") ? "PKCS12" : "JKS");
      trustStore.load(
          new FileInputStream(new File(trustPksFilename)), trustPksPassword.toCharArray());
      TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
      trustManagerFactory.init(trustStore);

      TLSClientParameters tlscp = new TLSClientParameters();
      tlscp.setSecureRandom(new SecureRandom());
      tlscp.setKeyManagers(keyManagerFactory.getKeyManagers());
      tlscp.setTrustManagers(trustManagerFactory.getTrustManagers());

      httpConduit.setTlsClientParameters(tlscp);
    }
  }
Example #17
0
 /**
  * Retrieves the keystore from the encoded data.
  *
  * @param type "PKCS12" or "JKS"
  * @param password to lock the keystore
  * @return the loaded and unlocked keystore.
  * @throws CertificateException
  * @throws IOException
  * @throws NoSuchAlgorithmException
  * @throws NoSuchProviderException
  * @throws KeyStoreException
  */
 public static java.security.KeyStore getKeyStore(
     byte[] keystoreData, String type, String password)
     throws CertificateException, NoSuchAlgorithmException, IOException, KeyStoreException,
         NoSuchProviderException {
   java.security.KeyStore ks =
       type.equalsIgnoreCase("JKS")
           ? java.security.KeyStore.getInstance("JKS")
           : java.security.KeyStore.getInstance(type, "BC");
   ByteArrayInputStream bais = new ByteArrayInputStream(Base64.decode(keystoreData));
   ks.load(bais, password.toCharArray());
   return ks;
 }
Example #18
0
 public static javax.net.SocketFactory getSSLFactory(
     java.lang.String s, java.lang.String s1, java.lang.StringBuffer stringbuffer) {
   javax.net.ssl.SSLSocketFactory sslsocketfactory = null;
   try {
     if (!(new File(s)).exists()) {
       throw new Exception("certificate not found");
     }
     java.security.KeyStore keystore;
     if (s.endsWith(".pfx")) {
       keystore = java.security.KeyStore.getInstance("PKCS12");
     } else {
       keystore = java.security.KeyStore.getInstance("JKS");
     }
     java.io.FileInputStream fileinputstream = new FileInputStream(s);
     char ac[] = s1.toCharArray();
     char ac1[] = s1.toCharArray();
     keystore.load(fileinputstream, ac);
     java.util.Enumeration enumeration = keystore.aliases();
     while (enumeration.hasMoreElements()) {
       java.lang.String s2 = (java.lang.String) enumeration.nextElement();
       certificateDescription = certificateDescription + " (" + s2;
       java.security.cert.Certificate acertificate[] = keystore.getCertificateChain(s2);
       if (acertificate != null) {
         int i = 0;
         while (i < acertificate.length) {
           java.security.cert.X509Certificate x509certificate =
               (java.security.cert.X509Certificate) acertificate[i];
           certificateDescription =
               certificateDescription
                   + " (cert "
                   + x509certificate.getSubjectDN()
                   + ", "
                   + x509certificate.getSigAlgName()
                   + ")";
           i++;
         }
       }
     }
     stringbuffer.append("certs: " + certificateDescription + "\n");
     com.sun.net.ssl.KeyManagerFactory keymanagerfactory =
         com.sun.net.ssl.KeyManagerFactory.getInstance("SunX509");
     keymanagerfactory.init(keystore, ac1);
     com.sun.net.ssl.KeyManager akeymanager[] = keymanagerfactory.getKeyManagers();
     com.sun.net.ssl.SSLContext sslcontext = com.sun.net.ssl.SSLContext.getInstance("SSL");
     sslcontext.init(akeymanager, null, randomGenerator);
     sslsocketfactory = sslcontext.getSocketFactory();
   } catch (java.lang.Throwable throwable) {
     throwable.printStackTrace();
     stringbuffer.append("error: " + throwable.toString());
   }
   return sslsocketfactory;
 }
  /*
   * 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 DockerCertificates(final Builder builder) throws DockerCertificateException {
    if ((builder.caCertPath == null)
        || (builder.clientCertPath == null)
        || (builder.clientKeyPath == null)) {
      throw new DockerCertificateException(
          "caCertPath, clientCertPath, and clientKeyPath must all be specified");
    }

    try {
      final CertificateFactory cf = CertificateFactory.getInstance("X.509");
      final Certificate caCert = cf.generateCertificate(Files.newInputStream(builder.caCertPath));
      final Certificate clientCert =
          cf.generateCertificate(Files.newInputStream(builder.clientCertPath));

      final PEMKeyPair clientKeyPair =
          (PEMKeyPair)
              new PEMParser(
                      Files.newBufferedReader(builder.clientKeyPath, Charset.defaultCharset()))
                  .readObject();

      final PKCS8EncodedKeySpec spec =
          new PKCS8EncodedKeySpec(clientKeyPair.getPrivateKeyInfo().getEncoded());
      final KeyFactory kf = KeyFactory.getInstance("RSA");
      final PrivateKey clientKey = kf.generatePrivate(spec);

      final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
      trustStore.load(null, null);
      trustStore.setEntry("ca", new KeyStore.TrustedCertificateEntry(caCert), null);

      final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
      keyStore.load(null, null);
      keyStore.setCertificateEntry("client", clientCert);
      keyStore.setKeyEntry("key", clientKey, KEY_STORE_PASSWORD, new Certificate[] {clientCert});

      this.sslContext =
          SSLContexts.custom()
              .loadTrustMaterial(trustStore)
              .loadKeyMaterial(keyStore, KEY_STORE_PASSWORD)
              .useTLS()
              .build();
    } catch (CertificateException
        | IOException
        | NoSuchAlgorithmException
        | InvalidKeySpecException
        | KeyStoreException
        | UnrecoverableKeyException
        | KeyManagementException e) {
      throw new DockerCertificateException(e);
    }
  }
  /** Default constructor. */
  public URIKeyStoreManager(String type, String provider, URI location)
      throws NoSuchProviderException, KeyStoreException {
    if (null == type) {
      type = DEFAULT_KEYSTORE_TYPE;
      provider = null;
    }

    // special case for forcing bc provider for jdk < 1.5 since jdk 1.4.x
    // jsse pkcs12 is readonly.
    if ("pkcs12".equalsIgnoreCase(type)) {
      if ("BC".equals(provider)) {
        provider = null;
      }

      boolean hasJDK15 =
          System.getProperty("java.specification.version", "0.0").compareTo("1.5") >= 0;

      provider = hasJDK15 ? null : "BC";
    }

    if (!location.isAbsolute()) {
      throw new IllegalArgumentException("location must be an absolute URI");
    }

    if ("file".equalsIgnoreCase(location.getScheme())) {
      File asFile = new File(location);

      if (asFile.exists() && !asFile.isFile()) {
        throw new IllegalArgumentException("location must refer to a file");
      }
    }

    if (LOG.isEnabledFor(Level.INFO)) {
      LOG.info("pse location = " + location);
    }

    keystore_type = type;

    keystore_provider = provider;

    keystore_location = location;

    // check if we can get an instance.
    if (null == keystore_provider) {
      KeyStore.getInstance(keystore_type);
    } else {
      KeyStore.getInstance(keystore_type, keystore_provider);
    }
  }
  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;
    }
  }
  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;
  }
Example #24
0
  /**
   * Loads key store from storage, or creates new one if storage is missing key store or corrupted.
   */
  private KeyStore load() {
    KeyStore keyStore;
    try {
      keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    } catch (KeyStoreException e) {
      throw new IllegalStateException("Unable to get default instance of KeyStore", e);
    }
    try {
      FileInputStream fis = mContext.openFileInput(KEYSTORE_FILENAME);
      keyStore.load(fis, KEYSTORE_PASSWORD);
    } catch (IOException e) {
      LogUtils.v("Unable open keystore file", e);
      keyStore = null;
    } catch (GeneralSecurityException e) {
      LogUtils.v("Unable open keystore file", e);
      keyStore = null;
    }

    if (keyStore != null) {
      // KeyStore loaded
      return keyStore;
    }

    try {
      keyStore = createKeyStore();
    } catch (GeneralSecurityException e) {
      throw new IllegalStateException("Unable to create identity KeyStore", e);
    }
    store(keyStore);
    return keyStore;
  }
 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;
 }
Example #26
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;
  }
 static KeyStore getKeyStore() throws Exception {
   InputStream in = new FileInputStream(new File(BASE, "rsakeys.ks"));
   KeyStore ks = KeyStore.getInstance("JKS");
   ks.load(in, password);
   in.close();
   return ks;
 }
 KeyStore.PrivateKeyEntry getKey()
     throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException,
         UnrecoverableEntryException {
   KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
   keyStore.load(null);
   return (PrivateKeyEntry) keyStore.getEntry(alias, null);
 }
  /** {@inheritDoc} */
  public boolean isInitialized(char[] store_password) {
    try {
      KeyStore store;
      if (null == keystore_provider) {
        store = KeyStore.getInstance(keystore_type);
      } else {
        store = KeyStore.getInstance(keystore_type, keystore_provider);
      }

      store.load(keystore_location.toURL().openStream(), store_password);

      return true;
    } catch (Exception failed) {
      return false;
    }
  }
Example #30
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");
  }