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);
      }
    }
Esempio n. 2
0
  @SuppressWarnings("deprecation")
  public static void main(String[] args)
      throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException,
          KeyManagementException, UnrecoverableKeyException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {
      KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
      FileInputStream fis =
          new FileInputStream("/home/gauravabbi/official/issues/cipherIssue/testHttpsKS");
      try {
        trustStore.load(fis, "password".toCharArray());
      } finally {
        try {
          fis.close();
        } catch (Exception e) {
          System.err.println(e.getStackTrace());
        }
      }

      SSLSocketFactory sslSocketFactory = new SSLSocketFactory(trustStore);

      Scheme scheme = new Scheme("https", 443, sslSocketFactory);
      httpclient.getConnectionManager().getSchemeRegistry().register(scheme);

      HttpGet getCall = new HttpGet("https://10.11.20.98:52080/test");
      HttpResponse response = httpclient.execute(getCall);

      System.out.println(response);
    } finally {
      httpclient.getConnectionManager().shutdown();
    }
  }
Esempio n. 3
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;
  }
Esempio n. 4
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");
  }
 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;
 }
Esempio n. 6
0
 public static String writeKeyStore(
     KeyStore keyStore,
     OutputStreamFactory outputStreamFactory,
     File file,
     String password,
     boolean generatedPassword)
     throws IOException, GeneralSecurityException {
   try (OutputStream fileOutputStream = outputStreamFactory.create(file)) {
     keyStore.store(fileOutputStream, password.toCharArray());
   } catch (IOException e) {
     if (e.getMessage().toLowerCase().contains(ILLEGAL_KEY_SIZE)
         && !isUnlimitedStrengthCryptographyEnabled()) {
       if (generatedPassword) {
         file.delete();
         String truncatedPassword = password.substring(0, 7);
         try (OutputStream fileOutputStream = outputStreamFactory.create(file)) {
           keyStore.store(fileOutputStream, truncatedPassword.toCharArray());
         }
         logTruncationWarning(file);
         return truncatedPassword;
       } else {
         throw new GeneralSecurityException(
             "Specified password for "
                 + file
                 + " too long to work without unlimited JCE policy installed."
                 + System.lineSeparator()
                 + "Please see "
                 + JCE_URL);
       }
     } else {
       throw e;
     }
   }
   return password;
 }
 KeyStore.PrivateKeyEntry getKey()
     throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException,
         UnrecoverableEntryException {
   KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
   keyStore.load(null);
   return (PrivateKeyEntry) keyStore.getEntry(alias, null);
 }
Esempio n. 8
0
 // Makes a trust store, suitable for backing a TrustManager, out of a CA cert
 // file.
 public static KeyStore trustStore(final String caCertFile)
     throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {
   final KeyStore keyStore = KeyStore.getInstance("JKS");
   keyStore.load(null, null);
   keyStore.setCertificateEntry("cacert", loadCertificate(caCertFile));
   return keyStore;
 }
  /**
   * @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;
    }
  }
  /**
   * 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. 11
0
  private static SSLSocketFactory getSocketFactory(Boolean d) {
    // Enable debug mode to ignore all certificates
    if (DEBUG) {
      KeyStore trustStore;
      try {
        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        SSLSocketFactory sf = new DebugSSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        return sf;

      } catch (KeyStoreException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
      } catch (NoSuchAlgorithmException e3) {
        // TODO Auto-generated catch block
        e3.printStackTrace();
      } catch (CertificateException e3) {
        // TODO Auto-generated catch block
        e3.printStackTrace();
      } catch (IOException e3) {
        // TODO Auto-generated catch block
        e3.printStackTrace();
      } catch (KeyManagementException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
      } catch (UnrecoverableKeyException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
      }
    }

    return SSLSocketFactory.getSocketFactory();
  }
  /** 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;
  }
  /**
   * Returns true if the given keystore can be loaded using the given keystore type and password.
   * Returns false otherwise.
   *
   * @param keystore the keystore to validate
   * @param keystoreType the type of the keystore
   * @param password the password to access the keystore
   * @return true if valid; false otherwise
   */
  public static boolean isStoreValid(
      final URL keystore, final KeystoreType keystoreType, final char[] password) {

    if (keystore == null) {
      throw new IllegalArgumentException("keystore may not be null");
    } else if (keystoreType == null) {
      throw new IllegalArgumentException("keystore type may not be null");
    } else if (password == null) {
      throw new IllegalArgumentException("password may not be null");
    }

    BufferedInputStream bis = null;
    final KeyStore ks;
    try {

      // load the keystore
      bis = new BufferedInputStream(keystore.openStream());
      ks = KeyStore.getInstance(keystoreType.name());
      ks.load(bis, password);

      return true;

    } catch (Exception e) {
      return false;
    } finally {
      if (bis != null) {
        try {
          bis.close();
        } catch (final IOException ioe) {
          logger.warn("Failed to close input stream", ioe);
        }
      }
    }
  }
 static KeyStore getKeystore() throws Exception {
   ClassLoader loader = SecureClientDriverTest.class.getClassLoader();
   byte[] binaryContent = IOUtils.toByteArray(loader.getResourceAsStream("keystore.jks"));
   KeyStore keyStore = KeyStore.getInstance("JKS");
   keyStore.load(new ByteArrayInputStream(binaryContent), "password".toCharArray());
   return keyStore;
 }
  /**
   * 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());
  }
  /** 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;
  }
Esempio n. 17
0
 /**
  * Load all X509 Certs from a key store File into a KeyStore Note that each call reinitializes the
  * KeyStore
  *
  * @return success
  * @since 0.8.2, moved from SSLEepGet in 0.9.9
  */
 private static boolean loadCerts(File file, KeyStore ks) {
   if (!file.exists()) return false;
   InputStream fis = null;
   try {
     fis = new FileInputStream(file);
     // "changeit" is the default password
     ks.load(fis, DEFAULT_KEYSTORE_PASSWORD.toCharArray());
     info("Certs loaded from " + file);
   } catch (GeneralSecurityException gse) {
     error("KeyStore load error, no default keys: " + file.getAbsolutePath(), gse);
     try {
       // not clear if null is allowed for password
       ks.load(null, DEFAULT_KEYSTORE_PASSWORD.toCharArray());
     } catch (Exception foo) {
     }
     return false;
   } catch (IOException ioe) {
     error("KeyStore load error, no default keys: " + file.getAbsolutePath(), ioe);
     try {
       ks.load(null, DEFAULT_KEYSTORE_PASSWORD.toCharArray());
     } catch (Exception foo) {
     }
     return false;
   } finally {
     try {
       if (fis != null) fis.close();
     } catch (IOException foo) {
     }
   }
   return true;
 }
Esempio n. 18
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;
  }
Esempio n. 19
0
 @BeforeClass
 public static void setUp() throws Exception {
   KEY = MessageDigest.getInstance("SHA-256").digest(ALIAS.getBytes());
   // Create a JKECS store containing a test secret key
   KeyStore store = KeyStore.getInstance("JCEKS");
   store.load(null, PASSWORD.toCharArray());
   store.setEntry(
       ALIAS,
       new KeyStore.SecretKeyEntry(new SecretKeySpec(KEY, "AES")),
       new KeyStore.PasswordProtection(PASSWORD.toCharArray()));
   // Create the test directory
   String dataDir = TEST_UTIL.getDataTestDir().toString();
   new File(dataDir).mkdirs();
   // Write the keystore file
   storeFile = new File(dataDir, "keystore.jks");
   FileOutputStream os = new FileOutputStream(storeFile);
   try {
     store.store(os, PASSWORD.toCharArray());
   } finally {
     os.close();
   }
   // Write the password file
   Properties p = new Properties();
   p.setProperty(ALIAS, PASSWORD);
   passwordFile = new File(dataDir, "keystore.pw");
   os = new FileOutputStream(passwordFile);
   try {
     p.store(os, "");
   } finally {
     os.close();
   }
 }
  private static HttpClient getNewHttpClient() {
    try {
      KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
      trustStore.load(null, null);

      SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
      sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

      HttpParams params = new BasicHttpParams();
      HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
      HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
      HttpConnectionParams.setConnectionTimeout(params, 10000);
      HttpConnectionParams.setSoTimeout(params, 20000);

      SchemeRegistry registry = new SchemeRegistry();
      registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
      registry.register(new Scheme("https", sf, 443));

      ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

      return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
      return new DefaultHttpClient();
    }
  }
Esempio n. 21
0
 @Override
 public int hashCode() {
   int result = keyStore != null ? keyStore.hashCode() : 0;
   result = 31 * result + (trustStore != null ? trustStore.hashCode() : 0);
   result = 31 * result + (trustStoreProvider != null ? trustStoreProvider.hashCode() : 0);
   result = 31 * result + (keyStoreProvider != null ? keyStoreProvider.hashCode() : 0);
   result = 31 * result + (trustStoreType != null ? trustStoreType.hashCode() : 0);
   result = 31 * result + (keyStoreType != null ? keyStoreType.hashCode() : 0);
   result = 31 * result + (trustStorePass != null ? Arrays.hashCode(trustStorePass) : 0);
   result = 31 * result + (keyStorePass != null ? Arrays.hashCode(keyStorePass) : 0);
   result = 31 * result + (keyPass != null ? Arrays.hashCode(keyPass) : 0);
   result = 31 * result + (trustStoreFile != null ? trustStoreFile.hashCode() : 0);
   result = 31 * result + (keyStoreFile != null ? keyStoreFile.hashCode() : 0);
   result = 31 * result + (trustStoreBytes != null ? Arrays.hashCode(trustStoreBytes) : 0);
   result = 31 * result + (keyStoreBytes != null ? Arrays.hashCode(keyStoreBytes) : 0);
   result =
       31 * result
           + (trustManagerFactoryAlgorithm != null ? trustManagerFactoryAlgorithm.hashCode() : 0);
   result =
       31 * result
           + (keyManagerFactoryAlgorithm != null ? keyManagerFactoryAlgorithm.hashCode() : 0);
   result =
       31 * result
           + (trustManagerFactoryProvider != null ? trustManagerFactoryProvider.hashCode() : 0);
   result =
       31 * result
           + (keyManagerFactoryProvider != null ? keyManagerFactoryProvider.hashCode() : 0);
   result = 31 * result + (securityProtocol != null ? securityProtocol.hashCode() : 0);
   return result;
 }
Esempio n. 22
0
 //	public static final char[] KEY_STORE_PASSWORD = "******".toCharArray();
 //	public static final long VALIDITY_PERIOD = 365 * 24 * 60 * 60 * 1000;
 //	public static final char[] KEY_PASSWORD = "******".toCharArray();
 //	public static String ROOT_ALIAS = "root";
 //	public static String INTERMEDIATE_ALIAS = "intermediate";
 //	public static String END_ENTITY_ALIAS = "end";
 //	public static final String KEY_STORE_PATH = ConfigurationClass.JAVA_KEY_STORE_PATH;
 //	public static final String SIGNED_DATA_PATH = "d:\\pkcs7\\SIGNED_DATA.sign";
 //	public static final String SIGNED_ENCRYPTED_DATA_PATH = "d:\\pkcs7\\SIGNED_ENC_DATA.sign";
 //	public static final String PLAIN_TEXT_FILE_PATH = "d:\\pkcs7\\PlainText.txt";
 //	public static final String RESULT_DATA_FILE_PATH = "d:\\pkcs7\\ResultData.txt";
 //	public static final String DECRYPTED_DATA_FILE_PATH = "d:\\pkcs7\\DECRYPTED_DATA.txt";
 public static KeyStore loadKeyStore() throws Exception {
   KeyStore keyStore = KeyStore.getInstance("JKS");
   InputStream is = new FileInputStream(new File(ConfigurationClass.JAVA_KEY_STORE_PATH));
   keyStore.load(is, ConfigurationClass.KEY_STORE_PASSWORD.toCharArray());
   is.close();
   return keyStore;
 }
Esempio n. 23
0
  /** {@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;
    }
  }
Esempio n. 24
0
  /**
   * Gets a KeyStore containing the Certificate
   *
   * @param cert InputStream of the Certificate
   * @return KeyStore
   */
  public static KeyStore getKeystoreOfCA(InputStream cert) {

    // Load CAs from an InputStream
    InputStream caInput = null;
    Certificate ca = null;
    try {
      CertificateFactory cf = CertificateFactory.getInstance("X.509");
      caInput = new BufferedInputStream(cert);
      ca = cf.generateCertificate(caInput);
    } catch (CertificateException e1) {
      e1.printStackTrace();
    } finally {
      try {
        if (caInput != null) {
          caInput.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    // Create a KeyStore containing our trusted CAs
    String keyStoreType = KeyStore.getDefaultType();
    KeyStore keyStore = null;
    try {
      keyStore = KeyStore.getInstance(keyStoreType);
      keyStore.load(null, null);
      keyStore.setCertificateEntry("ca", ca);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return keyStore;
  }
Esempio n. 25
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;
  }
  /** java.security.KeyStore#containsAlias(java.lang.String) */
  public void test_containsAliasLjava_lang_String() throws Exception {
    // Test for method boolean
    // java.security.KeyStore.containsAlias(java.lang.String)
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509Certificate cert[] = new X509Certificate[2];
    cert[0] = (X509Certificate) cf.generateCertificate(certArray);
    cert[1] = (X509Certificate) cf.generateCertificate(certArray2);
    KeyStore keyTest = KeyStore.getInstance(KeyStore.getDefaultType());

    try {
      keyTest.containsAlias("alias1");
      fail();
    } catch (KeyStoreException expected) {
    }

    keyTest.load(null, null);

    // alias 1
    keyTest.setCertificateEntry("alias1", cert[0]);

    // alias 2
    keyTest.setCertificateEntry("alias2", cert[0]);

    assertTrue("alias1 does not exist", keyTest.containsAlias("alias1"));
    assertTrue("alias2 does not exist", keyTest.containsAlias("alias2"));
    assertFalse("alias3 exists", keyTest.containsAlias("alias3"));

    try {
      keyTest.containsAlias(null);
      fail();
    } catch (NullPointerException expected) {
    }
  }
Esempio n. 27
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;
 }
Esempio n. 28
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;
  }
  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;
  }
Esempio n. 30
0
  /**
   * Returns the private key for the specified ID.
   *
   * @param id The ID of the requested private key.
   * @param key_password The passphrase associated with the private key or {@code null} if the key
   *     has no passphrase.
   * @return PrivateKey for the specified ID.
   * @throws KeyStoreException When the wrong keystore has been provided.
   * @throws IOException For errors related to processing the keystore.
   */
  public PrivateKey getKey(ID id, char[] key_password) throws KeyStoreException, IOException {

    String alias = id.toString();

    try {
      synchronized (keystore_manager) {
        KeyStore store = keystore_manager.loadKeyStore(keystore_password);

        if (!store.containsAlias(alias) || !store.isKeyEntry(alias)) {
          return null;
        }

        return (PrivateKey) store.getKey(alias, key_password);
      }

    } catch (NoSuchAlgorithmException failed) {

      Logging.logCheckedSevere(LOG, "Something failed\n", failed);

      KeyStoreException failure = new KeyStoreException("Something Failed");

      failure.initCause(failed);
      throw failure;

    } catch (UnrecoverableKeyException failed) {

      Logging.logCheckedSevere(LOG, "Key passphrase failure\n", failed);

      KeyStoreException failure = new KeyStoreException("Key passphrase failure");
      failure.initCause(failed);
      throw failure;
    }
  }