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;
 }
 private static KeyStore readKeyStore(String name) throws Exception {
   File file = new File(PATH, name);
   InputStream in = new FileInputStream(file);
   KeyStore ks = KeyStore.getInstance("JKS");
   ks.load(in, passwd);
   in.close();
   return ks;
 }
  public static HttpClient getCertifiedHttpClient() throws IDPTokenManagerException {
    HttpClient client = null;
    InputStream inStream = null;
    try {
      if (Constants.SERVER_PROTOCOL.equalsIgnoreCase("https://")) {
        KeyStore localTrustStore = KeyStore.getInstance("BKS");
        inStream =
            IdentityProxy.getInstance()
                .getContext()
                .getResources()
                .openRawResource(R.raw.emm_truststore);
        localTrustStore.load(inStream, Constants.TRUSTSTORE_PASSWORD.toCharArray());

        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(
            new Scheme("http", PlainSocketFactory.getSocketFactory(), Constants.HTTP));
        SSLSocketFactory sslSocketFactory = new SSLSocketFactory(localTrustStore);
        sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        schemeRegistry.register(new Scheme("https", sslSocketFactory, Constants.HTTPS));
        HttpParams params = new BasicHttpParams();
        ClientConnectionManager connectionManager =
            new ThreadSafeClientConnManager(params, schemeRegistry);

        client = new DefaultHttpClient(connectionManager, params);

      } else {
        client = new DefaultHttpClient();
      }

    } catch (KeyStoreException e) {
      String errorMsg = "Error occurred while accessing keystore.";
      Log.e(TAG, errorMsg);
      throw new IDPTokenManagerException(errorMsg, e);
    } catch (CertificateException e) {
      String errorMsg = "Error occurred while loading certificate.";
      Log.e(TAG, errorMsg);
      throw new IDPTokenManagerException(errorMsg, e);
    } catch (NoSuchAlgorithmException e) {
      String errorMsg = "Error occurred while due to mismatch of defined algorithm.";
      Log.e(TAG, errorMsg);
      throw new IDPTokenManagerException(errorMsg, e);
    } catch (UnrecoverableKeyException e) {
      String errorMsg = "Error occurred while accessing keystore.";
      Log.e(TAG, errorMsg);
      throw new IDPTokenManagerException(errorMsg, e);
    } catch (KeyManagementException e) {
      String errorMsg = "Error occurred while accessing keystore.";
      Log.e(TAG, errorMsg);
      throw new IDPTokenManagerException(errorMsg, e);
    } catch (IOException e) {
      String errorMsg = "Error occurred while loading trust store. ";
      Log.e(TAG, errorMsg);
      throw new IDPTokenManagerException(errorMsg, e);
    } finally {
      StreamHandlerUtil.closeInputStream(inStream, TAG);
    }
    return client;
  }
Exemple #4
0
  /**
   * Initialisation if a supplied key is defined in the properties. This supplied key must be in a
   * keystore which can be generated using the keystoreGenerator file in demos. The keystore must be
   * on the classpath to find it.
   *
   * @throws KeyStoreException
   * @throws Exception
   * @throws IOException
   * @throws NoSuchAlgorithmException
   * @throws CertificateException
   * @throws UnrecoverableKeyException
   */
  private void initConfiguredKey() throws Exception {
    InputStream inputStream = null;
    // must not use default keystore type - as does not support secret keys
    KeyStore store = KeyStore.getInstance("JCEKS");

    SecretKey tempKey = null;
    try {
      // load in keystore using this thread's classloader
      inputStream =
          Thread.currentThread().getContextClassLoader().getResourceAsStream(keyStoreName);
      if (inputStream == null) inputStream = new FileInputStream(keyStoreName);
      // we can't find a keystore here -
      if (inputStream == null) {
        throw new Exception(
            "Unable to load keystore " + keyStoreName + " ensure file is on classpath");
      }
      // we have located a file lets load the keystore
      try {
        store.load(inputStream, storePassword.toCharArray());
        // loaded keystore - get the key
        tempKey = (SecretKey) store.getKey(alias, keyPassword.toCharArray());
      } catch (IOException e) {
        throw new Exception("Unable to load keystore " + keyStoreName + ": " + e);
      } catch (NoSuchAlgorithmException e) {
        throw new Exception("No Such algorithm " + keyStoreName + ": " + e);
      } catch (CertificateException e) {
        throw new Exception("Certificate exception " + keyStoreName + ": " + e);
      }

      if (tempKey == null)
        throw new Exception("Unable to retrieve key '" + alias + "' from keystore " + keyStoreName);
      // set the key here
      setSecretKey(tempKey);

      if (symAlgorithm.equals(DEFAULT_SYM_ALGO)) symAlgorithm = tempKey.getAlgorithm();

      // set the fact we are using a supplied key
      suppliedKey = true;
      queue_down = queue_up = false;
    } finally {
      Util.close(inputStream);
    }
  }
 public boolean load(String storeName, String storeType, String passwd) throws DigiDocException {
   FileInputStream fis = null;
   try {
     if (m_logger.isDebugEnabled())
       m_logger.debug("Load store: " + storeName + " type: " + storeType);
     m_keyStore = KeyStore.getInstance(storeType);
     if (m_keyStore != null) {
       m_keyStore.load(fis = new FileInputStream(storeName), passwd.toCharArray());
       return true;
     }
   } catch (Exception ex) {
     m_logger.error("Error loading store: " + storeName + " - " + ex);
   } finally {
     if (fis != null) {
       try {
         fis.close();
         fis = null;
       } catch (Exception ex2) {
         m_logger.error("Error closing pkcs12: " + storeName + " - " + ex2);
       }
     }
   }
   return false;
 }
 KeyStore loadKeyStore(String type, File file, String passwd) throws Exception {
   KeyStore ks = KeyStore.getInstance(type);
   FileInputStream fis = new FileInputStream(file);
   ks.load(fis, passwd.toCharArray());
   return ks;
 }
Exemple #7
0
  public void signJar(Jar jar) {
    if (digestNames == null || digestNames.length == 0)
      error("Need at least one digest algorithm name, none are specified");

    if (keystoreFile == null || !keystoreFile.getAbsoluteFile().exists()) {
      error("No such keystore file: " + keystoreFile);
      return;
    }

    if (alias == null) {
      error("Private key alias not set for signing");
      return;
    }

    MessageDigest digestAlgorithms[] = new MessageDigest[digestNames.length];

    getAlgorithms(digestNames, digestAlgorithms);

    try {
      Manifest manifest = jar.getManifest();
      manifest.getMainAttributes().putValue("Signed-By", "Bnd");

      // Create a new manifest that contains the
      // Name parts with the specified digests

      ByteArrayOutputStream o = new ByteArrayOutputStream();
      manifest.write(o);
      doManifest(jar, digestNames, digestAlgorithms, o);
      o.flush();
      byte newManifestBytes[] = o.toByteArray();
      jar.putResource("META-INF/MANIFEST.MF", new EmbeddedResource(newManifestBytes, 0));

      // Use the bytes from the new manifest to create
      // a signature file

      byte[] signatureFileBytes = doSignatureFile(digestNames, digestAlgorithms, newManifestBytes);
      jar.putResource("META-INF/BND.SF", new EmbeddedResource(signatureFileBytes, 0));

      // Now we must create an RSA signature
      // this requires the private key from the keystore

      KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());

      KeyStore.PrivateKeyEntry privateKeyEntry = null;

      java.io.FileInputStream keystoreInputStream = null;
      try {
        keystoreInputStream = new java.io.FileInputStream(keystoreFile);
        char[] pw = password == null ? new char[0] : password.toCharArray();

        keystore.load(keystoreInputStream, pw);
        keystoreInputStream.close();
        privateKeyEntry =
            (PrivateKeyEntry) keystore.getEntry(alias, new KeyStore.PasswordProtection(pw));
      } catch (Exception e) {
        error(
            "No able to load the private key from the give keystore("
                + keystoreFile.getAbsolutePath()
                + ") with alias "
                + alias
                + " : "
                + e);
        return;
      } finally {
        IO.close(keystoreInputStream);
      }
      PrivateKey privateKey = privateKeyEntry.getPrivateKey();

      Signature signature = Signature.getInstance("MD5withRSA");
      signature.initSign(privateKey);

      signature.update(signatureFileBytes);

      signature.sign();

      // TODO, place the SF in a PCKS#7 structure ...
      // no standard class for this? The following
      // is an idea but we will to have do ASN.1 BER
      // encoding ...

      ByteArrayOutputStream tmpStream = new ByteArrayOutputStream();
      jar.putResource("META-INF/BND.RSA", new EmbeddedResource(tmpStream.toByteArray(), 0));
    } catch (Exception e) {
      error("During signing: " + e);
    }
  }
Exemple #8
0
  public static synchronized void setGlobalSSLAuth(
      String keypath, String keypassword, String trustpath, String trustpassword) {
    // load the stores if defined
    try {
      if (trustpath != null && trustpassword != null) {
        truststore = KeyStore.getInstance(KeyStore.getDefaultType());
        try (FileInputStream instream = new FileInputStream(new File(trustpath))) {
          truststore.load(instream, trustpassword.toCharArray());
        }
      } else truststore = null;
      if (keypath != null && keypassword != null) {
        keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        try (FileInputStream instream = new FileInputStream(new File(keypath))) {
          keystore.load(instream, keypassword.toCharArray());
        }
      } else keystore = null;
    } catch (IOException | NoSuchAlgorithmException | CertificateException | KeyStoreException ex) {
      log.error("Illegal -D keystore parameters: " + ex.getMessage());
      truststore = null;
      keystore = null;
    }
    try {
      // set up the context
      SSLContext scxt = null;
      if (IGNORECERTS) {
        scxt = SSLContext.getInstance("TLS");
        TrustManager[] trust_mgr =
            new TrustManager[] {
              new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                  return null;
                }

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

                public void checkServerTrusted(X509Certificate[] certs, String t) {}
              }
            };
        scxt.init(
            null, // key manager
            trust_mgr, // trust manager
            new SecureRandom()); // random number generator
      } else {
        SSLContextBuilder sslbuilder = SSLContexts.custom();
        TrustStrategy strat = new LooseTrustStrategy();
        if (truststore != null) sslbuilder.loadTrustMaterial(truststore, strat);
        else sslbuilder.loadTrustMaterial(strat);
        sslbuilder.loadTrustMaterial(truststore, new LooseTrustStrategy());
        if (keystore != null) sslbuilder.loadKeyMaterial(keystore, keypassword.toCharArray());
        scxt = sslbuilder.build();
      }
      globalsslfactory = new SSLConnectionSocketFactory(scxt, new NoopHostnameVerifier());

      RegistryBuilder rb = RegistryBuilder.<ConnectionSocketFactory>create();
      rb.register("https", globalsslfactory);
      sslregistry = rb.build();
    } catch (KeyStoreException
        | NoSuchAlgorithmException
        | KeyManagementException
        | UnrecoverableEntryException e) {
      log.error("Failed to set key/trust store(s): " + e.getMessage());
      sslregistry = null;
      globalsslfactory = null;
    }
  }