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. 2
0
 /**
  * Creates an empty keystore
  *
  * @throws Exception
  */
 private void createKeystore() throws Exception {
   if (keystore == null) {
     Security.addProvider(bouncyCastleProvider);
     keystore =
         KeyStore.getInstance(Configuration.getSSLClientKeyStoreType(), bouncyCastleProvider);
     keystore.load(null, KEYSTORE_PASSWORD.toCharArray());
   }
 }
Esempio n. 3
0
 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;
 }
Esempio n. 4
0
  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;
  }
Esempio n. 5
0
 public void testDefaults() throws Exception {
   Properties p = initProps();
   KeyStore ks = KeyStoreUtil.createKeyStore(p);
   List aliases = ListUtil.fromIterator(new EnumerationIterator(ks.aliases()));
   assertIsomorphic(SetUtil.set("mykey", "mycert"), SetUtil.theSet(aliases));
   assertNotNull(ks.getCertificate("mycert"));
   assertNull(ks.getCertificate("foocert"));
   assertEquals("JCEKS", ks.getType());
 }
Esempio n. 6
0
 void assertPubKs(File file, String pass, List<String> hosts) throws Exception {
   KeyStore ks = loadKeyStore("jceks", file, pass);
   List aliases = ListUtil.fromIterator(new EnumerationIterator(ks.aliases()));
   assertEquals(hosts.size(), aliases.size());
   for (String host : hosts) {
     String alias = host + ".crt";
     Certificate cert = ks.getCertificate(alias);
     assertNotNull(cert);
     assertEquals("X.509", cert.getType());
   }
 }
  /*
   * Define the client side of the test.
   *
   * If the server prematurely exits, serverReady will be set to true
   * to avoid infinite hangs.
   */
  void doClientSide() throws Exception {

    /*
     * Wait for server to get started.
     */
    while (!serverReady) {
      Thread.sleep(50);
    }

    /*
     * See if an unknown keystore actually gets checked ok.
     */
    System.out.println("==============");
    System.out.println("Starting test0");
    KeyStore uks = KeyStore.getInstance("JKS");
    SSLContext ctx = SSLContext.getInstance("TLS");
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");

    uks.load(new FileInputStream(unknownFilename), cpasswd);
    kmf.init(uks, cpasswd);

    TrustManager[] tms = new TrustManager[] {new MyJavaxX509TrustManager()};

    ctx.init(kmf.getKeyManagers(), tms, null);

    SSLSocketFactory sslsf = (SSLSocketFactory) ctx.getSocketFactory();

    System.out.println("Trying first socket " + serverPort);
    SSLSocket sslSocket = (SSLSocket) sslsf.createSocket("localhost", serverPort);

    doTest(sslSocket);

    /*
     * Now try the other way.
     */
    com.sun.net.ssl.SSLContext ctx1 = com.sun.net.ssl.SSLContext.getInstance("TLS");
    com.sun.net.ssl.KeyManagerFactory kmf1 =
        com.sun.net.ssl.KeyManagerFactory.getInstance("SunX509");
    kmf1.init(uks, cpasswd);

    com.sun.net.ssl.TrustManager[] tms1 =
        new com.sun.net.ssl.TrustManager[] {new MyComX509TrustManager()};

    ctx1.init(kmf1.getKeyManagers(), tms1, null);

    sslsf = (SSLSocketFactory) ctx1.getSocketFactory();

    System.out.println("Trying second socket " + serverPort1);
    sslSocket = (SSLSocket) sslsf.createSocket("localhost", serverPort1);

    doTest(sslSocket);
    System.out.println("Completed test1");
  }
  public static void main(String args[]) {

    int port = 6502;
    SSLServerSocket server;

    try {
      // get the keystore into memory
      KeyStore ks = KeyStore.getInstance("JKS");
      ks.load(new FileInputStream(keyStore), keyStorePass);

      // initialize the key manager factory with the keystore data
      KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
      kmf.init(ks, keyStorePass);

      // initialize the SSLContext engine
      // may throw NoSuchProvider or NoSuchAlgorithm exception
      // TLS - Transport Layer Security most generic

      SSLContext sslContext = SSLContext.getInstance("TLS");

      // Inititialize context with given KeyManagers, TrustManagers,
      // SecureRandom defaults taken if null

      sslContext.init(kmf.getKeyManagers(), null, null);

      // Get ServerSocketFactory from the context object
      ServerSocketFactory ssf = sslContext.getServerSocketFactory();
      //  Now like programming with normal server sockets
      ServerSocket serverSocket = ssf.createServerSocket(port);

      System.out.println("Accepting secure connections");

      Socket client = serverSocket.accept();
      System.out.println("Got connection");

      BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
      BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
      String username = in.readLine();
      String password = in.readLine();

      if (username.equals("Josh") && password.equals("GoBucs")) {
        out.write("Greeting Client");
      } else {
        out.write("Sorry, you are not authorized");
      }
      out.flush();
      in.close();
      out.close();
    } catch (Exception e) {
      System.out.println("Exception thrown " + e);
    }
  }
Esempio n. 9
0
 @Test
 public void testSelfSignedCertificate() throws Exception {
   KeyStore keystore = createKeyStore();
   KeyStoreUtil.updateWithSelfSignedServerCertificate(keystore);
   X509Certificate cert = (X509Certificate) keystore.getCertificate("jolokia-agent");
   assertNotNull(cert);
   assertEquals(
       cert.getSubjectDN().getName(),
       "CN=Jolokia Agent "
           + Version.getAgentVersion()
           + ", OU=JVM, O=jolokia.org, L=Pegnitz, ST=Franconia, C=DE");
   assertEquals(cert.getSubjectDN(), cert.getIssuerDN());
 }
Esempio n. 10
0
 private void createClientKeyStore() throws Exception {
   clientCertKeystore = KeyStore.getInstance(Configuration.getSSLClientKeyStoreType());
   String clientCertPath = Configuration.getSSLClientCertPath();
   FileInputStream fileInputStream = null;
   if (clientCertPath != null) {
     try {
       fileInputStream = new FileInputStream(clientCertPath);
     } catch (IOException ioe) {
       logger.error("\n----\nCertificate not found: " + clientCertPath + "\n----");
     }
   }
   String password = Configuration.getSSLClientCertPassword();
   char[] passphrase = password == null ? null : password.toCharArray();
   clientCertKeystore.load(fileInputStream, passphrase);
 }
Esempio n. 11
0
 private X509Certificate buildSignedCert(String domain, KeyPair _keyPair) throws Exception {
   PrivateKey privateRootKey =
       (PrivateKey)
           keystore.getKey(Configuration.getRootCaName(), KEYSTORE_PASSWORD.toCharArray());
   X509v3CertificateBuilder certificateBuilder = createX509v3CertificateBuilder(domain, _keyPair);
   return createX509Certificate(certificateBuilder, privateRootKey);
 }
 /**
  * Method decrypts the data with the RSA private key corresponding to this certificate (which was
  * used to encrypt it). Decryption will be done with keystore
  *
  * @param data data to be decrypted.
  * @param token index of authentication token
  * @param pin PIN code
  * @return decrypted data.
  * @throws DigiDocException for all decryption errors
  */
 public byte[] decrypt(byte[] data, int token, String pin) throws DigiDocException {
   try {
     if (m_keyStore == null)
       throw new DigiDocException(
           DigiDocException.ERR_NOT_INITED, "Keystore not initialized", null);
     String alias = getTokenName(token);
     if (alias == null)
       throw new DigiDocException(
           DigiDocException.ERR_TOKEN_LOGIN, "Invalid token nr: " + token, null);
     // get key
     if (m_logger.isDebugEnabled())
       m_logger.debug(
           "loading key: " + alias + " passwd-len: " + ((pin != null) ? pin.length() : 0));
     Key key = m_keyStore.getKey(alias, pin.toCharArray());
     if (m_logger.isDebugEnabled())
       m_logger.debug("Key: " + ((key != null) ? "OK, algorithm: " + key.getAlgorithm() : "NULL"));
     if (key == null)
       throw new DigiDocException(
           DigiDocException.ERR_TOKEN_LOGIN, "Invalid password for token: " + alias, null);
     Cipher cipher = Cipher.getInstance("RSA");
     cipher.init(Cipher.DECRYPT_MODE, key);
     byte[] decdata = cipher.doFinal(data);
     if (m_logger.isDebugEnabled())
       m_logger.debug("Decrypted len: " + ((decdata != null) ? decdata.length : 0));
     return decdata;
   } catch (Exception ex) {
     m_logger.error("Error decrypting: " + ex);
   }
   return null;
 }
Esempio n. 13
0
 private void addCertToKeystore(X509Certificate _cert, Key _privateKey, String alias)
     throws KeyStoreException {
   X509Certificate[] chain = new X509Certificate[2];
   chain[0] = _cert;
   chain[1] = rootCA;
   keystore.setKeyEntry(alias, _privateKey, KEYSTORE_PASSWORD.toCharArray(), chain);
 }
Esempio n. 14
0
  /*
   * If this is a secure server, we now setup the SSLContext we'll
   * use for creating the SSLEngines throughout the lifetime of
   * this process.
   */
  private void createSSLContext() throws Exception {

    char[] passphrase = "passphrase".toCharArray();

    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(new FileInputStream("testkeys"), passphrase);

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

    TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
    tmf.init(ks);

    sslContext = SSLContext.getInstance("TLS");
    sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
  }
Esempio n. 15
0
  @Test
  public void testTrustStore()
      throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException {
    File caPem = getTempFile("ca/cert.pem");
    KeyStore keystore = createKeyStore();

    KeyStoreUtil.updateWithCaPem(keystore, caPem);

    Enumeration<String> aliases = keystore.aliases();
    String alias = aliases.nextElement();
    assertFalse(aliases.hasMoreElements());
    assertTrue(alias.contains("ca.test.jolokia.org"));
    X509Certificate cert = (X509Certificate) keystore.getCertificate(alias);
    cert.checkValidity();
    assertTrue(cert.getSubjectDN().getName().contains(CA_CERT_SUBJECT_DN_CN));
    RSAPublicKey key = (RSAPublicKey) cert.getPublicKey();
    assertEquals(key.getAlgorithm(), "RSA");
  }
Esempio n. 16
0
 private static void loadKeyStore(File keyStoreFile) {
   try {
     FileInputStream fileInputStream = null;
     try {
       fileInputStream = new FileInputStream(KEY_STORE_FILENAME);
       logger.trace("Loading key store from file [" + keyStoreFile + "]");
       keystore = KeyStore.getInstance(KeyStore.getDefaultType());
       keystore.load(fileInputStream, KEY_STORE_PASSWORD.toCharArray());
     } finally {
       if (fileInputStream != null) {
         fileInputStream.close();
       }
     }
   } catch (Exception e) {
     throw new RuntimeException(
         "Exception while loading KeyStore from " + keyStoreFile.getAbsolutePath(), e);
   }
 }
Esempio n. 17
0
  @Test
  public void testBoth()
      throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException,
          InvalidKeySpecException, InvalidKeyException, NoSuchProviderException,
          SignatureException {
    File caPem = getTempFile("ca/cert.pem");
    File serverPem = getTempFile("server/cert.pem");
    File keyPem = getTempFile("server/key.pem");

    KeyStore keystore = createKeyStore();
    KeyStoreUtil.updateWithCaPem(keystore, caPem);
    KeyStoreUtil.updateWithServerPems(keystore, serverPem, keyPem, "RSA", new char[0]);

    X509Certificate caCert = (X509Certificate) keystore.getCertificate(CA_ALIAS);
    X509Certificate serverCert = (X509Certificate) keystore.getCertificate(SERVER_ALIAS);

    // Check that server cert is signed by ca
    serverCert.verify(caCert.getPublicKey());
  }
Esempio n. 18
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);
    }
  }
Esempio n. 19
0
  public void testCreateSharedPLNKeyStores() throws Exception {
    List<String> hosts = ListUtil.list("host1", "host2.foo.bar", "host3");
    List<String> hosts2 = ListUtil.list("host3", "host4");
    File dir = getTempDir();
    File pub = new File(dir, "pub.ks");
    KeyStoreUtil.createSharedPLNKeyStores(
        dir, hosts, pub, "pubpass", MiscTestUtil.getSecureRandom());
    assertPubKs(pub, "pubpass", hosts);
    for (String host : hosts) {
      assertPrivateKs(
          new File(dir, host + ".jceks"), StringUtil.fromFile(new File(dir, host + ".pass")), host);
    }
    KeyStore pubks1 = loadKeyStore("jceks", new File(dir, "pub.ks"), "pubpass");

    Certificate host1cert1 = pubks1.getCertificate("host1.crt");
    Certificate host3cert1 = pubks1.getCertificate("host3.crt");

    String host1priv1 = StringUtil.fromFile(new File(dir, "host1.jceks"));
    String host3priv1 = StringUtil.fromFile(new File(dir, "host3.jceks"));

    // Now add host4 and generate a new key for host3
    KeyStoreUtil.createSharedPLNKeyStores(
        dir, hosts2, pub, "pubpass", MiscTestUtil.getSecureRandom());
    List<String> both = ListUtils.sum(hosts, hosts2);
    assertPubKs(pub, "pubpass", both);
    for (String host : both) {
      assertPrivateKs(
          new File(dir, host + ".jceks"), StringUtil.fromFile(new File(dir, host + ".pass")), host);
    }
    KeyStore pubks2 = loadKeyStore("jceks", new File(dir, "pub.ks"), "pubpass");
    // host1 should have the same cert, host3 not
    Certificate host1cert2 = pubks2.getCertificate("host1.crt");
    Certificate host3cert2 = pubks2.getCertificate("host3.crt");
    assertEquals(host1cert1, host1cert2);
    assertNotEquals(host3cert1, host3cert2);

    // host1's private key file should be the same, host3's not
    String host1priv2 = StringUtil.fromFile(new File(dir, "host1.jceks"));
    String host3priv2 = StringUtil.fromFile(new File(dir, "host3.jceks"));
    assertEquals(host1priv1, host1priv2);
    assertNotEquals(host3priv1, host3priv2);
  }
Esempio n. 20
0
 /**
  * We need a root CA as a file to add to the browser under which all certificates will be trusted.
  *
  * @throws Exception
  */
 private void createRootCA() throws Exception {
   KeyPair _keyPair = newKeyPair();
   rootCA = buildRootCert(Configuration.getRootCaName(), _keyPair);
   writePEMObject(rootCAPath, rootCA);
   writePEMObject(Configuration.getRootKeyPath(), _keyPair.getPrivate());
   keystore.setKeyEntry(
       Configuration.getRootCaName(),
       _keyPair.getPrivate(),
       KEYSTORE_PASSWORD.toCharArray(),
       new X509Certificate[] {rootCA});
 }
Esempio n. 21
0
 private void loadKeyStoreFromFile(KeyStore pKeyStore, String pFile, char[] pPassword)
     throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {
   FileInputStream fis = null;
   try {
     fis = new FileInputStream(getAndValidateFile(pFile, "keystore"));
     pKeyStore.load(fis, pPassword);
   } finally {
     if (fis != null) {
       fis.close();
     }
   }
 }
Esempio n. 22
0
  public boolean createSelfSignedKeystore(
      String cn,
      String keystoreFile,
      String keystorePassword,
      String privateKeyPassword,
      String privateKeyAlias) {
    KeyStore ks = null;

    try {
      ks = KeyStore.getInstance("JKS");
      ks.load(null, null);

      KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");
      keyGen.initialize(1024, new SecureRandom());
      KeyPair keypair = keyGen.generateKeyPair();
      PrivateKey privkey = keypair.getPrivate();
      PublicKey pubkey = keypair.getPublic();

      Hashtable<DERObjectIdentifier, String> attrs = new Hashtable<DERObjectIdentifier, String>();
      Vector<DERObjectIdentifier> ordering = new Vector<DERObjectIdentifier>();
      ordering.add(X509Name.CN);
      attrs.put(X509Name.CN, cn);
      X509Name issuerDN = new X509Name(ordering, attrs);
      X509Name subjectDN = new X509Name(ordering, attrs);

      Date validFrom = new Date();
      validFrom.setTime(validFrom.getTime() - (10 * 60 * 1000));
      Date validTo = new Date();
      validTo.setTime(validTo.getTime() + (20 * (24 * 60 * 60 * 1000)));

      X509V3CertificateGenerator x509 = new X509V3CertificateGenerator();
      x509.setSignatureAlgorithm("SHA1withDSA");
      x509.setIssuerDN(issuerDN);
      x509.setSubjectDN(subjectDN);
      x509.setPublicKey(pubkey);
      x509.setNotBefore(validFrom);
      x509.setNotAfter(validTo);
      x509.setSerialNumber(new BigInteger(128, new Random()));

      X509Certificate[] cert = new X509Certificate[1];
      cert[0] = x509.generate(privkey, "BC");
      java.security.cert.Certificate[] chain = new java.security.cert.Certificate[1];
      chain[0] = cert[0];

      ks.setKeyEntry(privateKeyAlias, privkey, privateKeyPassword.toCharArray(), cert);
      ks.setKeyEntry(privateKeyAlias, privkey, privateKeyPassword.toCharArray(), chain);
      ks.store(new FileOutputStream(keystoreFile), keystorePassword.toCharArray());

      String IDP_RFC_CERT = "WEB-INF/guanxi_idp/keystore/guanxi_idp_cert.txt";

      PEMWriter pemWriter = new PEMWriter(new FileWriter(servletContext.getRealPath(IDP_RFC_CERT)));
      pemWriter.writeObject(cert[0]);
      pemWriter.close();

      return true;
    } catch (Exception se) {
      return false;
    }
  }
 /**
  * Method returns a X.509 certificate object readed from the active token and representing an user
  * public key certificate value.
  *
  * @return X.509 certificate object.
  * @throws DigiDocException if getting X.509 public key certificate fails or the requested
  *     certificate type X.509 is not available in the default provider package
  */
 public X509Certificate getCertificate(int token, String pin) throws DigiDocException {
   if (m_keyStore == null)
     throw new DigiDocException(DigiDocException.ERR_NOT_INITED, "Keystore not initialized", null);
   String alias = getTokenName(token);
   if (alias == null)
     throw new DigiDocException(
         DigiDocException.ERR_TOKEN_LOGIN, "Invalid token nr: " + token, null);
   try {
     return (X509Certificate) m_keyStore.getCertificate(alias);
   } catch (Exception ex) {
     m_logger.error("Error reading cert for alias: " + alias + " - " + ex);
   }
   return null;
 }
Esempio n. 24
0
 /**
  * Read certificate and adds it to the keystore.
  *
  * @throws IOException
  * @throws CertificateException
  * @throws KeyStoreException
  */
 private void readRootCA() throws IOException, CertificateException, KeyStoreException {
   Key _privateKey = readPrivateKey(Configuration.getRootKeyPath());
   X509CertificateHolder holder =
       (X509CertificateHolder) readWithPemParser(Configuration.getRootCaPath());
   rootCA =
       new JcaX509CertificateConverter()
           .setProvider(BouncyCastleProvider.PROVIDER_NAME)
           .getCertificate(holder);
   keystore.setKeyEntry(
       Configuration.getRootCaName(),
       _privateKey,
       KEYSTORE_PASSWORD.toCharArray(),
       new X509Certificate[] {rootCA});
 }
 /**
  * Returns the n-th token name or alias
  *
  * @param nIdx index of token
  * @return alias
  */
 private String getTokenName(int nIdx) {
   try {
     if (m_keyStore != null) {
       Enumeration eAliases = m_keyStore.aliases();
       for (int i = 0; eAliases.hasMoreElements(); i++) {
         String alias = (String) eAliases.nextElement();
         if (i == nIdx) return alias;
       }
     }
   } catch (Exception ex) {
     m_logger.error("Error reading store aliases: " + ex);
   }
   return null;
 }
  public void main(Provider p) throws Exception {

    /*
     * Use Solaris SPARC 11.2 or later to avoid an intermittent failure
     * when running SunPKCS11-Solaris (8044554)
     */
    if (p.getName().equals("SunPKCS11-Solaris")
        && System.getProperty("os.name").equals("SunOS")
        && System.getProperty("os.arch").equals("sparcv9")
        && System.getProperty("os.version").compareTo("5.11") <= 0
        && getDistro().compareTo("11.2") < 0) {

      System.out.println(
          "SunPKCS11-Solaris provider requires " + "Solaris SPARC 11.2 or later, skipping");
      return;
    }

    long start = System.currentTimeMillis();
    provider = p;
    data = new byte[2048];
    new Random().nextBytes(data);
    KeyStore ks = getKeyStore();
    KeyFactory kf = KeyFactory.getInstance("RSA", provider);
    for (Enumeration e = ks.aliases(); e.hasMoreElements(); ) {
      String alias = (String) e.nextElement();
      if (ks.isKeyEntry(alias)) {
        System.out.println("* Key " + alias + "...");
        PrivateKey privateKey = (PrivateKey) ks.getKey(alias, password);
        PublicKey publicKey = ks.getCertificate(alias).getPublicKey();
        privateKey = (PrivateKey) kf.translateKey(privateKey);
        publicKey = (PublicKey) kf.translateKey(publicKey);
        test(privateKey, publicKey);
      }
    }
    long stop = System.currentTimeMillis();
    System.out.println("All tests passed (" + (stop - start) + " ms).");
  }
 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;
 }
Esempio n. 28
0
  @Test
  public void testKeyStore()
      throws IOException, CertificateException, NoSuchAlgorithmException, KeyStoreException,
          InvalidKeySpecException, UnrecoverableKeyException {
    File serverPem = getTempFile("server/cert.pem");
    File keyPem = getTempFile("server/key.pem");
    KeyStore keystore = createKeyStore();

    KeyStoreUtil.updateWithServerPems(keystore, serverPem, keyPem, "RSA", new char[0]);

    Enumeration<String> aliases = keystore.aliases();
    String alias = aliases.nextElement();
    assertFalse(aliases.hasMoreElements());

    assertTrue(alias.contains("server"));

    X509Certificate cert = (X509Certificate) keystore.getCertificate(alias);
    cert.checkValidity();
    assertEquals(cert.getSubjectDN().getName(), SERVER_CERT_SUBJECT_DN);
    RSAPrivateCrtKey key = (RSAPrivateCrtKey) keystore.getKey(alias, new char[0]);
    assertEquals("RSA", key.getAlgorithm());
    RSAPublicKey pubKey = (RSAPublicKey) cert.getPublicKey();
    assertEquals("RSA", pubKey.getAlgorithm());
  }
Esempio n. 29
0
  private KeyStore getKeyStore(JolokiaServerConfig pConfig)
      throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException,
          InvalidKeySpecException, InvalidKeyException, NoSuchProviderException,
          SignatureException {
    char[] password = pConfig.getKeystorePassword();
    String keystoreFile = pConfig.getKeystore();
    KeyStore keystore = KeyStore.getInstance(pConfig.getKeyStoreType());
    if (keystoreFile != null) {
      // Load everything from a keystore which must include CA (if useClientSslAuthenticatin is
      // used) and
      // server cert/key
      loadKeyStoreFromFile(keystore, keystoreFile, password);
    } else {
      // Load keys from PEM files
      keystore.load(null);
      updateKeyStoreFromPEM(keystore, pConfig);

      // If no server cert is configured, then use a self-signed server certificate
      if (pConfig.getServerCert() == null) {
        KeyStoreUtil.updateWithSelfSignedServerCertificate(keystore);
      }
    }
    return keystore;
  }
 /**
  * Method returns an array of strings representing the list of available token names.
  *
  * @return an array of available token names.
  * @throws DigiDocException if reading the token information fails.
  */
 public String[] getAvailableTokenNames() throws DigiDocException {
   Vector vec = new Vector();
   try {
     if (m_keyStore != null) {
       Enumeration eAliases = m_keyStore.aliases();
       while (eAliases.hasMoreElements()) {
         String alias = (String) eAliases.nextElement();
         vec.add(alias);
       }
     }
   } catch (Exception ex) {
     m_logger.error("Error reading store aliases: " + ex);
   }
   String[] arr = new String[vec.size()];
   for (int i = 0; (vec != null) && (i < vec.size()); i++) arr[i] = (String) vec.elementAt(i);
   return arr;
 }