/**
   * Manipulates a PDF file src with the file dest as result
   *
   * @param src the original PDF
   * @param dest the resulting PDF
   * @throws IOException
   * @throws DocumentException
   * @throws GeneralSecurityException
   */
  public void signPdf(String src, String dest, boolean withTS, boolean withOCSP)
      throws IOException, DocumentException, GeneralSecurityException {
    // Keystore and certificate chain
    // String keystore = properties.getProperty("PRIVATE");
    String keystore = "c://ks3.p12";
    // String password = properties.getProperty("PASSWORD");
    String password = "******";
    KeyStore ks = KeyStore.getInstance("PKCS12", "BC");
    ks.load(new FileInputStream(keystore), password.toCharArray());
    String alias = (String) ks.aliases().nextElement();
    PrivateKey pk = (PrivateKey) ks.getKey(alias, password.toCharArray());
    Certificate[] chain = ks.getCertificateChain(alias);
    // reader and stamper
    PdfReader reader = new PdfReader(src);
    FileOutputStream fout = new FileOutputStream(dest);

    PdfStamper stp = PdfStamper.createSignature(reader, fout, '\0');

    // appearance
    PdfSignatureAppearance sap = stp.getSignatureAppearance();
    sap.setReason("I'm approving this.");
    sap.setLocation("Foobar");
    sap.setVisibleSignature(new Rectangle(72, 732, 144, 780), 1, "Signature12");
    // preserve some space for the contents
    // digital signature
    ExternalSignature es = new PrivateKeySignature(pk, "SHA-256", "BC");
    // If we add a time stamp:
    TSAClient tsc = null;

    // System.setProperty("http.proxyHost", "10.3.8.1");
    // System.setProperty("http.proxyPort", "80");

    if (false) {
      String tsa_url = "https://tsa.jefatura.gob.ar:318"; // properties.getProperty("TSA");
      String tsa_login = "******"; // properties.getProperty("TSA_LOGIN");
      String tsa_passw = "jmc1159"; // properties.getProperty("TSA_PASSWORD");
      tsc = new TSAClientBouncyCastle(tsa_url); // , tsa_login, tsa_passw);
    }
    // If we use OCSP:
    OcspClient ocsp = null;
    if (withOCSP) {
      ocsp = new OcspClientBouncyCastle();
    }
    ExternalDigest digest = new BouncyCastleDigest();
    MakeSignature.signDetached(sap, digest, es, chain, null, null, tsc, 0, CryptoStandard.CMS);
  }
 /**
  * Method creating a connection to the webservice using the information stored in the property
  * files.
  *
  * @throws IOException
  * @throws FileNotFoundException
  */
 protected XKMSInvoker getXKMSInvoker() throws FileNotFoundException, IOException {
   if (xkms == null) {
     if (getKeyStorePath() != null) {
       try {
         KeyStore clientKeyStore = KeyStore.getInstance("JKS");
         clientKeyStore.load(
             new FileInputStream(getKeyStorePath()), getKeyStorePassword().toCharArray());
         if (getKeyStoreAlias() == null) {
           throw new IOException("Error no alias specified in the property file");
         }
         String alias = getKeyStoreAlias();
         clientCert = (java.security.cert.X509Certificate) clientKeyStore.getCertificate(alias);
         privateKey = clientKeyStore.getKey(alias, getKeyStorePassword().toCharArray());
         Certificate[] trustedcerts = clientKeyStore.getCertificateChain(alias);
         catrustlist = new ArrayList<Certificate>();
         for (int i = 0; i < trustedcerts.length; i++) {
           if (((X509Certificate) trustedcerts[i]).getBasicConstraints() != -1) {
             catrustlist.add(trustedcerts[i]);
           }
         }
       } catch (Exception e) {
         throw new IOException("Error reading client keystore " + e.getMessage());
       }
     }
     xkms = new XKMSInvoker(getWebServiceURL(), catrustlist);
   }
   return xkms;
 }
Exemple #3
0
  /**
   * Process the input stream and try to read the keys from the store
   *
   * @param is {@link InputStream} from which the store should be loaded
   * @param pword the password used to check the integrity of the store
   * @throws IOException if there is a problem decoding or reading the store. A bad password might
   *     be the cause for this, or an empty store
   * @throws CertificateException if any of the certificated in the store can not be loaded
   * @throws NoSuchAlgorithmException if the algorithm to check the integrity of the store can not
   *     be found
   * @throws KeyStoreException if the store has not been initialized (should not happen here)
   * @throws UnrecoverableKeyException if the key can not be recovered from the store (should not
   *     happen here, either)
   */
  public void load(InputStream is, String pword)
      throws NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException,
          UnrecoverableKeyException {
    char pw[] = pword == null ? null : pword.toCharArray();
    store.load(is, pw);

    ArrayList<String> v_names = new ArrayList<String>();
    this.privateKeyByAlias = new HashMap<String, PrivateKey>();
    this.certsByAlias = new HashMap<String, X509Certificate[]>();

    if (null != is) { // No point checking an empty keystore
      PrivateKey _key = null;
      int index = 0;
      Enumeration<String> aliases = store.aliases();
      while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        if (store.isKeyEntry(alias)) {
          if (index >= startIndex && index <= endIndex) {
            _key = (PrivateKey) store.getKey(alias, pw);
            if (null == _key) {
              throw new IOException("No key found for alias: " + alias); // Should not happen
            }
            Certificate[] chain = store.getCertificateChain(alias);
            if (null == chain) {
              throw new IOException("No certificate chain found for alias: " + alias);
            }
            v_names.add(alias);
            X509Certificate[] x509certs = new X509Certificate[chain.length];
            for (int i = 0; i < x509certs.length; i++) {
              x509certs[i] = (X509Certificate) chain[i];
            }

            privateKeyByAlias.put(alias, _key);
            certsByAlias.put(alias, x509certs);
          }
          index++;
        }
      }

      if (null == _key) {
        throw new IOException("No key(s) found");
      }
      if (index <= endIndex - startIndex) {
        LOG.warn(
            "Did not find all requested aliases. Start="
                + startIndex
                + ", end="
                + endIndex
                + ", found="
                + certsByAlias.size());
      }
    }

    /*
     * Note: if is == null, the arrays will be empty
     */
    this.names = v_names.toArray(new String[v_names.size()]);
  }
  @Test
  public void testMutualAuthenticationWithDNSInCNField() throws Exception {
    // Although specifying a DNS name using the Common Name field has been deprecated, it is
    // still used in practice (e.g., see http://tools.ietf.org/html/rfc2818). This test makes
    // sure that general name matching during authentication still works in this case.
    final SaslClientFactory clientFactory = obtainSaslClientFactory(EntitySaslClientFactory.class);
    assertNotNull(clientFactory);

    final KeyStore keyStore = loadKeyStore(serverKeyStore);
    final Certificate[] certificateChain = keyStore.getCertificateChain("dnsInCNServer");
    final SaslServer saslServer =
        createSaslServer(
            SaslMechanismInformation.Names.IEC_ISO_9798_M_DSA_SHA1,
            "testserver2.example.com",
            getX509TrustManager(serverTrustStore),
            (PrivateKey) keyStore.getKey("dnsInCNServer", KEYSTORE_PASSWORD),
            Arrays.copyOf(certificateChain, certificateChain.length, X509Certificate[].class));

    final String[] mechanisms =
        new String[] {SaslMechanismInformation.Names.IEC_ISO_9798_M_DSA_SHA1};
    CallbackHandler cbh =
        createClientCallbackHandler(
            mechanisms,
            clientKeyStore,
            "dnsInCNClient",
            KEYSTORE_PASSWORD,
            getX509TrustManager(clientTrustStore));
    final SaslClient saslClient =
        clientFactory.createSaslClient(
            mechanisms,
            null,
            "test",
            "testserver2.example.com",
            Collections.<String, Object>emptyMap(),
            cbh);
    assertFalse(saslServer.isComplete());
    assertFalse(saslClient.isComplete());

    byte[] message = saslServer.evaluateResponse(new byte[0]);
    assertFalse(saslServer.isComplete());
    assertFalse(saslClient.isComplete());

    message = saslClient.evaluateChallenge(message);
    assertFalse(saslServer.isComplete());
    assertFalse(saslClient.isComplete());

    message = saslServer.evaluateResponse(message);
    assertNotNull(message);

    message = saslClient.evaluateChallenge(message);
    assertNull(message);
    assertTrue(saslClient.isComplete());
    assertTrue(saslServer.isComplete());
    assertEquals(
        "cn=testclient2.example.com,ou=jboss,o=red hat,l=raleigh,st=north carolina,c=us",
        saslServer.getAuthorizationID());
  }
  /**
   * set up the ssl connectors with strong ciphers
   *
   * @throws Exception
   */
  protected void initConnectors() throws Exception {
    if (!_disableHTTP) {
      if (_unsecuredConnector == null) {
        _unsecuredConnector = new SelectChannelConnector();
      }
      if (_unsecurePort != null) {
        _unsecuredConnector.setPort(Integer.parseInt(_unsecurePort));
      } else {
        _unsecuredConnector.setPort(_serviceInfo.getEndpoint().getPort());
      }
      if (_httpBindAddress != null) {
        _unsecuredConnector.setHost(_httpBindAddress);
      }
      if (lowResourcesConnections != null) {
        _unsecuredConnector.setLowResourcesConnections(lowResourcesConnections);
      }
      if (lowResourcesMaxIdleTime != null) {
        _unsecuredConnector.setLowResourcesMaxIdleTime(lowResourcesMaxIdleTime);
      }
      if (threadPool != null) {
        _unsecuredConnector.setThreadPool(threadPool);
      }
      _server.addConnector(_unsecuredConnector);
    }
    if (!_disableSSL) {
      SslContextFactory sslFac = new SslContextFactory();
      sslFac.setIncludeCipherSuites(_ciphers);

      KeyStore ks = KeyStoreUtil.getViPRKeystore(_coordinatorClient);
      _log.debug(
          "The certificates in Jetty is {}. ",
          ks.getCertificateChain(KeystoreEngine.ViPR_KEY_AND_CERTIFICATE_ALIAS));

      sslFac.setCertAlias(KeystoreEngine.ViPR_KEY_AND_CERTIFICATE_ALIAS);
      sslFac.setKeyStore(ks);
      _securedConnector = new SslSelectChannelConnector(sslFac);
      if (_securePort != null) {
        _securedConnector.setPort(Integer.parseInt(_securePort));
      } else {
        _securedConnector.setPort(_serviceInfo.getEndpoint().getPort());
      }
      if (_bindAddress != null) {
        _securedConnector.setHost(_bindAddress);
      }
      if (lowResourcesConnections != null) {
        _securedConnector.setLowResourcesConnections(lowResourcesConnections);
      }
      if (lowResourcesMaxIdleTime != null) {
        _securedConnector.setLowResourcesMaxIdleTime(lowResourcesMaxIdleTime);
      }
      if (threadPool != null) {
        _securedConnector.setThreadPool(threadPool);
      }
      _server.addConnector(_securedConnector);
    }
    _server.setSendServerVersion(false);
  }
  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();
  }
  @Override
  public List<X509Certificate> getCertificates() {

    List<X509Certificate> certificates = new ArrayList<X509Certificate>();
    try {

      KeyStore keyStore = KeyStore.getInstance(keyStoreType);
      keyStore.load(new FileInputStream(keyStoreFile), password.toCharArray());
      Enumeration<String> aliases = keyStore.aliases();
      while (aliases.hasMoreElements()) {

        String alias = aliases.nextElement();

        Certificate onecert = keyStore.getCertificate(alias);
        LOG.fine("Alias " + alias + " Cert " + ((X509Certificate) onecert).getSubjectDN());
        if (onecert != null) {

          certificates.add((X509Certificate) onecert);
        }
        if (keyStore.getCertificateChain(alias) != null) {

          for (Certificate cert : keyStore.getCertificateChain(alias)) {

            LOG.fine("Alias " + alias + " Cert " + ((X509Certificate) cert).getSubjectDN());
            if (!certificates.contains(cert)) {

              certificates.add((X509Certificate) cert);
            }
          }
        }
      }
    } catch (CertificateException e) {
      throw new EncodingException(MSG.CERTIFICATE_CANNOT_BE_READ);
    } catch (KeyStoreException e) {
      throw new EncodingException(MSG.CERTIFICATE_CANNOT_BE_READ);
    } catch (NoSuchAlgorithmException e) {
      throw new EncodingException(MSG.CERTIFICATE_CANNOT_BE_READ);
    } catch (FileNotFoundException e) {
      throw new EncodingException(MSG.CERTIFICATE_CANNOT_BE_READ);
    } catch (IOException e) {
      throw new EncodingException(MSG.CERTIFICATE_CANNOT_BE_READ);
    }
    return certificates;
  }
  /** java.security.KeyStore#getCertificateChain(java.lang.String) */
  public void test_getCertificateChainLjava_lang_String() throws Exception {
    // Test for method java.security.cert.Certificate[]
    // java.security.KeyStore.getCertificateChain(java.lang.String)
    // creatCertificate();
    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.getCertificateChain("anAlias");
      fail();
    } catch (KeyStoreException expected) {
    }

    keyTest.load(null, null);

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

    // alias 2
    keyTest.setKeyEntry("alias2", getPrivateKey(), pssWord, cert);

    Certificate[] certRes = keyTest.getCertificateChain("alias2");
    assertEquals(
        "there are more than two certificate returned from getCertificateChain", 2, certRes.length);
    assertEquals(
        "the first certificate returned from getCertificateChain is not correct",
        cert[0].getPublicKey(),
        certRes[0].getPublicKey());
    assertEquals(
        "the second certificate returned from getCertificateChain is not correct",
        cert[1].getPublicKey(),
        certRes[1].getPublicKey());
    Certificate[] certResNull = keyTest.getCertificateChain("alias1");
    assertNull("the certificate chain returned from getCertificateChain is NOT null", certResNull);

    try {
      keyTest.getCertificateChain(null);
      fail();
    } catch (NullPointerException expected) {
    }
  }
  /**
   * Loads the given keyStore (location specified in Californium.properties). The keyStore must
   * contain the private key and the corresponding certificate (chain). The keyStore alias is
   * expected to be "client".
   */
  protected void loadKeyStore() {
    try {
      KeyStore keyStore = KeyStore.getInstance("JKS");
      InputStream in = new FileInputStream(DTLSConnector.KEY_STORE_LOCATION);
      keyStore.load(in, KEY_STORE_PASSWORD.toCharArray());

      certificates = keyStore.getCertificateChain("client");
      privateKey = (PrivateKey) keyStore.getKey("client", KEY_STORE_PASSWORD.toCharArray());
    } catch (Exception e) {
      LOGGER.log(Level.SEVERE, "Could not load the keystore.", e);
    }
  }
  public static Cipher getCipherOfSuperTenant() throws UserStoreException {
    Cipher cipher;
    ServerConfigurationService config = UserStoreConfigComponent.getServerConfigurationService();

    if (config == null) {
      String errMsg = "ServerConfigurationService is null - this situation can't occur";
      throw new UserStoreException(errMsg);
    }

    String filePath = config.getFirstProperty(UserStoreConfigurationConstants.SERVER_KEYSTORE_FILE);
    String keyStoreType =
        config.getFirstProperty(UserStoreConfigurationConstants.SERVER_KEYSTORE_TYPE);
    String password =
        config.getFirstProperty(UserStoreConfigurationConstants.SERVER_KEYSTORE_PASSWORD);
    String keyAlias =
        config.getFirstProperty(UserStoreConfigurationConstants.SERVER_KEYSTORE_KEY_ALIAS);

    KeyStore store;
    InputStream inputStream = null;

    try {
      inputStream = new FileInputStream(new File(filePath).getAbsolutePath());
      store = KeyStore.getInstance(keyStoreType);
      store.load(inputStream, password.toCharArray());
      Certificate[] certs = store.getCertificateChain(keyAlias);
      cipher = Cipher.getInstance("RSA", "BC");
      cipher.init(Cipher.ENCRYPT_MODE, certs[0].getPublicKey());
    } catch (FileNotFoundException e) {
      String errorMsg = "Keystore File Not Found in configured location";
      throw new UserStoreException(errorMsg, e);
    } catch (IOException e) {
      String errorMsg = "Keystore File IO operation failed";
      throw new UserStoreException(errorMsg, e);
    } catch (InvalidKeyException e) {
      String errorMsg = "Invalid key is used to access keystore";
      throw new UserStoreException(errorMsg, e);
    } catch (KeyStoreException e) {
      String errorMsg = "Faulty keystore";
      throw new UserStoreException(errorMsg, e);
    } catch (GeneralSecurityException e) {
      String errorMsg = "Some parameters assigned to access the " + "keystore is invalid";
      throw new UserStoreException(errorMsg, e);
    } finally {
      if (inputStream != null) {
        try {
          inputStream.close();
        } catch (IOException e) {
          log.error("Key store file closing failed");
        }
      }
    }
    return cipher;
  }
Exemple #11
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;
 }
Exemple #12
0
  public void loadPrimaryKey() {
    try {
      KeyStore keyStore = KeyStore.getInstance("JKS");
      keyStore.load(new FileInputStream("mytestkey.jks"), "password".toCharArray());

      Key key = keyStore.getKey("alias", "password".toCharArray());
      // System.out.println("Private key : "+key.toString()); //You will
      // get a NullPointerException if you uncomment this line

      java.security.cert.Certificate[] chain = keyStore.getCertificateChain("mykey");
      for (java.security.cert.Certificate cert : chain) {
        System.out.println(cert.toString());
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
  public void buildSignedMultiReleaseJar() throws Exception {
    String testsrc = System.getProperty("test.src", ".");
    String testdir = findTestDir(testsrc);
    String keystore = testdir + "/sun/security/tools/jarsigner/JarSigning.keystore";

    // jarsigner -keystore keystore -storepass "bbbbbb"
    //           -signedJar signed-multi-release.jar multi-release.jar b

    char[] password = "******".toCharArray();
    KeyStore ks = KeyStore.getInstance(new File(keystore), password);
    PrivateKey pkb = (PrivateKey) ks.getKey("b", password);
    CertPath cp =
        CertificateFactory.getInstance("X.509")
            .generateCertPath(Arrays.asList(ks.getCertificateChain("b")));
    JarSigner js = new JarSigner.Builder(pkb, cp).build();
    try (ZipFile in = new ZipFile("multi-release.jar");
        FileOutputStream os = new FileOutputStream("signed-multi-release.jar")) {
      js.sign(in, os);
    }
  }
  public void addPrivateKey(
      @Nonnull @Nonempty final String sAlias,
      @Nonnull final Key aKey,
      @Nonnull final String sPassword)
      throws OpenAS2Exception {
    ValueEnforcer.notEmpty(sAlias, "Alias");
    ValueEnforcer.notNull(aKey, "Key");
    ValueEnforcer.notNull(sPassword, "Password");

    final KeyStore aKeyStore = getKeyStore();
    try {
      if (!aKeyStore.containsAlias(sAlias)) throw new CertificateNotFoundException(null, sAlias);

      final Certificate[] aCertChain = aKeyStore.getCertificateChain(sAlias);
      aKeyStore.setKeyEntry(sAlias, aKey, sPassword.toCharArray(), aCertChain);
      save(getFilename(), getPassword());
    } catch (final GeneralSecurityException ex) {
      throw WrappedOpenAS2Exception.wrap(ex);
    }
  }
  @Ignore // todo: this test could be modified to use the wrong key of the write algorithm, or it
          // could be removed
  @Test
  public void testServerPrivateKeyPublicKeyMismatch() throws Exception {
    final SaslClientFactory clientFactory = obtainSaslClientFactory(EntitySaslClientFactory.class);
    assertNotNull(clientFactory);

    // A certificate that does not correspond to the server's private key will be used
    final KeyStore keyStore = loadKeyStore(serverKeyStore);
    final Certificate[] certificateChain = keyStore.getCertificateChain(WRONG_KEYSTORE_ALIAS);
    final SaslServer saslServer =
        createSaslServer(
            SaslMechanismInformation.Names.IEC_ISO_9798_M_RSA_SHA1_ENC,
            "testserver1.example.com",
            getX509TrustManager(serverTrustStore),
            (PrivateKey) keyStore.getKey(SERVER_KEYSTORE_ALIAS, KEYSTORE_PASSWORD),
            Arrays.copyOf(certificateChain, certificateChain.length, X509Certificate[].class));

    final String[] mechanisms =
        new String[] {SaslMechanismInformation.Names.IEC_ISO_9798_M_RSA_SHA1_ENC};
    CallbackHandler cbh =
        createClientCallbackHandler(
            mechanisms,
            clientKeyStore,
            CLIENT_KEYSTORE_ALIAS,
            KEYSTORE_PASSWORD,
            getX509TrustManager(clientTrustStore));
    final SaslClient saslClient =
        clientFactory.createSaslClient(
            mechanisms, null, "test", "", Collections.<String, Object>emptyMap(), cbh);

    byte[] message = saslServer.evaluateResponse(new byte[0]);
    message = saslClient.evaluateChallenge(message);
    message = saslServer.evaluateResponse(message);
    try {
      saslClient.evaluateChallenge(message);
      fail("Expected SaslException not thrown");
    } catch (SaslException expected) {
    }
  }
 private void logKeyStore(KeyStore store) throws KeyStoreException {
   LOG.trace("Certificates count: " + store.size());
   Enumeration aliases = store.aliases();
   while (aliases.hasMoreElements()) {
     String alias = (String) aliases.nextElement();
     Certificate[] certs = store.getCertificateChain(alias);
     if (certs != null) {
       LOG.debug("Certificate chain '" + alias + "':");
       for (int c = 0; c < certs.length; c++) {
         if (certs[c] instanceof X509Certificate) {
           X509Certificate cert = (X509Certificate) certs[c];
           LOG.trace(" Certificate " + (c + 1) + ":");
           LOG.trace("  Subject DN: " + cert.getSubjectDN());
           LOG.trace("  Signature Algorithm: " + cert.getSigAlgName());
           LOG.trace("  Valid from: " + cert.getNotBefore());
           LOG.trace("  Valid until: " + cert.getNotAfter());
           LOG.trace("  Issuer: " + cert.getIssuerDN());
         }
       }
     }
   }
 }
  // read key store data
  private static KeyPair readKeyStore(CredentialDescriptor cd) throws IOException {
    KeyPair kp = null;
    InputStream is = null;

    try {
      KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
      char[] stsKeystorePassword = cd.getPassword().toCharArray();
      is = getInputStream(cd.getFilename());
      ks.load(is, stsKeystorePassword);

      kp = new KeyPair();
      kp.setCertificateChain(Arrays.asList(ks.getCertificateChain(cd.getAlias())));
      kp.setPrivateKey((PrivateKey) ks.getKey(cd.getAlias(), stsKeystorePassword));
    } catch (Exception e) {
      logger.debug("Caught exception while reading keystore {}", e.toString());
    } finally {
      if (is != null) {
        is.close();
      }
    }

    return kp;
  }
Exemple #18
0
  /**
   * Returns the trusted cert chain for the specified id.
   *
   * @param id The ID of the certificate who's certificate chain is desired.
   * @return Certificate chain for the specified ID or null if the PSE does not contain the
   *     specified certificate.
   * @throws KeyStoreException When the wrong keystore has been provided.
   * @throws IOException For errors related to processing the keystore.
   */
  public X509Certificate[] getTrustedCertificateChain(ID id) throws KeyStoreException, IOException {

    String alias = id.toString();

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

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

      Certificate certs[] = store.getCertificateChain(alias);

      if (null == certs) {
        return null;
      }

      X509Certificate x509certs[] = new X509Certificate[certs.length];

      System.arraycopy(certs, 0, x509certs, 0, certs.length);

      return x509certs;
    }
  }
  /**
   * Sign file.
   *
   * @param signingDTO sign informations
   * @param pdfSignedFile signed pdf returned
   */
  public void sign(final DigitalSigningDTO signingDTO) {
    if (signingDTO != null) {

      try {
        Security.addProvider(new BouncyCastleProvider());
        final File alfTempDir = TempFileProvider.getTempDir();

        if (alfTempDir != null) {
          final String keyType =
              (String) nodeService.getProperty(signingDTO.getKeyFile(), SigningModel.PROP_KEYTYPE);

          if (SigningConstants.KEY_TYPE_X509.equals(keyType)) {
            // Sign the file
            final KeyStore ks = KeyStore.getInstance("pkcs12");
            final ContentReader keyContentReader = getReader(signingDTO.getKeyFile());

            if (keyContentReader != null && ks != null && signingDTO.getKeyPassword() != null) {

              final List<AlfrescoRuntimeException> errors =
                  new ArrayList<AlfrescoRuntimeException>();

              // Get crypted secret key and decrypt it
              final Serializable encryptedPropertyValue =
                  nodeService.getProperty(
                      signingDTO.getKeyFile(), SigningModel.PROP_KEYCRYPTSECRET);
              final Serializable decryptedPropertyValue =
                  metadataEncryptor.decrypt(
                      SigningModel.PROP_KEYCRYPTSECRET, encryptedPropertyValue);

              // Decrypt key content
              InputStream decryptedKeyContent;
              try {
                decryptedKeyContent =
                    CryptUtils.decrypt(
                        decryptedPropertyValue.toString(),
                        keyContentReader.getContentInputStream());
              } catch (Throwable e) {
                log.error(e);
                throw new AlfrescoRuntimeException(e.getMessage(), e);
              }

              ks.load(
                  new ByteArrayInputStream(IOUtils.toByteArray(decryptedKeyContent)),
                  signingDTO.getKeyPassword().toCharArray());

              final String alias =
                  (String)
                      nodeService.getProperty(signingDTO.getKeyFile(), SigningModel.PROP_KEYALIAS);

              final PrivateKey key =
                  (PrivateKey) ks.getKey(alias, signingDTO.getKeyPassword().toCharArray());
              final Certificate[] chain = ks.getCertificateChain(alias);

              final Iterator<NodeRef> itFilesToSign = signingDTO.getFilesToSign().iterator();
              while (itFilesToSign.hasNext()) {
                final NodeRef nodeRefToSign = itFilesToSign.next();
                final AlfrescoRuntimeException exception =
                    signFile(nodeRefToSign, signingDTO, alfTempDir, alias, ks, key, chain);
                if (exception != null) {
                  // Error on the file process
                  errors.add(exception);
                }
              }

              if (errors != null && errors.size() > 0) {
                final StringBuffer allErrors = new StringBuffer();
                final Iterator<AlfrescoRuntimeException> itErrors = errors.iterator();
                if (errors.size() > 1) {
                  allErrors.append("\n");
                }
                while (itErrors.hasNext()) {
                  final AlfrescoRuntimeException alfrescoRuntimeException = itErrors.next();
                  allErrors.append(alfrescoRuntimeException.getMessage());
                  if (itErrors.hasNext()) {
                    allErrors.append("\n");
                  }
                }
                throw new RuntimeException(allErrors.toString());
              }

            } else {
              log.error("Unable to get key content, key type or key password.");
              throw new AlfrescoRuntimeException(
                  "Unable to get key content, key type or key password.");
            }
          }
        } else {
          log.error("Unable to get temporary directory.");
          throw new AlfrescoRuntimeException("Unable to get temporary directory.");
        }
      } catch (KeyStoreException e) {
        log.error(e);
        throw new AlfrescoRuntimeException(e.getMessage(), e);
      } catch (NoSuchAlgorithmException e) {
        log.error(e);
        throw new AlfrescoRuntimeException(e.getMessage(), e);
      } catch (CertificateException e) {
        log.error(e);
        throw new AlfrescoRuntimeException(e.getMessage(), e);
      } catch (IOException e) {
        log.error(e);
        throw new AlfrescoRuntimeException(e.getMessage(), e);
      } catch (UnrecoverableKeyException e) {
        log.error(e);
        throw new AlfrescoRuntimeException(e.getMessage(), e);
      }
    } else {
      log.error("No object with signing informations.");
      throw new AlfrescoRuntimeException("No object with signing informations.");
    }
  }
  /** Do action. */
  @Override
  protected void doAction() {
    FileOutputStream fos = null;
    File caReplyFile = null;

    try {
      KeyStoreHistory history = kseFrame.getActiveKeyStoreHistory();
      KeyStoreState currentState = history.getCurrentState();

      String alias = kseFrame.getSelectedEntryAlias();

      Password password = getEntryPassword(alias, currentState);

      if (password == null) {
        return;
      }

      KeyStore keyStore = currentState.getKeyStore();

      PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, password.toCharArray());
      Certificate[] certs = keyStore.getCertificateChain(alias);

      KeyPairType keyPairType = KeyPairUtil.getKeyPairType(privateKey);

      File csrFile = chooseCsrFile();
      if (csrFile == null) {
        return;
      }

      PKCS10CertificationRequest pkcs10Csr = null;
      Spkac spkacCsr = null;

      try {
        CryptoFileType fileType = CryptoFileUtil.detectFileType(new FileInputStream(csrFile));
        if (fileType == CryptoFileType.PKCS10_CSR) {
          pkcs10Csr = Pkcs10Util.loadCsr(new FileInputStream(csrFile));

          if (!Pkcs10Util.verifyCsr(pkcs10Csr)) {
            JOptionPane.showMessageDialog(
                frame,
                res.getString("SignCsrAction.NoVerifyPkcs10Csr.message"),
                res.getString("SignCsrAction.SignCsr.Title"),
                JOptionPane.WARNING_MESSAGE);
            return;
          }
        } else if (fileType == CryptoFileType.SPKAC_CSR) {
          spkacCsr = new Spkac(new FileInputStream(csrFile));

          if (!spkacCsr.verify()) {
            JOptionPane.showMessageDialog(
                frame,
                res.getString("SignCsrAction.NoVerifySpkacCsr.message"),
                res.getString("SignCsrAction.SignCsr.Title"),
                JOptionPane.WARNING_MESSAGE);
            return;
          }
        } else {
          JOptionPane.showMessageDialog(
              frame,
              MessageFormat.format(
                  res.getString("SignCsrAction.FileNotRecognisedType.message"), csrFile),
              res.getString("SignCsrAction.SignCsr.Title"),
              JOptionPane.WARNING_MESSAGE);
          return;
        }
      } catch (FileNotFoundException ex) {
        JOptionPane.showMessageDialog(
            frame,
            MessageFormat.format(res.getString("SignCsrAction.NotFile.message"), csrFile),
            res.getString("SignCsrAction.SignCsr.Title"),
            JOptionPane.WARNING_MESSAGE);
        return;
      } catch (Exception ex) {
        String problemStr =
            MessageFormat.format(
                res.getString("SignCsrAction.NoOpenCsr.Problem"), csrFile.getName());

        String[] causes =
            new String[] {
              res.getString("SignCsrAction.NotCsr.Cause"),
              res.getString("SignCsrAction.CorruptedCsr.Cause")
            };

        Problem problem = new Problem(problemStr, causes, ex);

        DProblem dProblem =
            new DProblem(frame, res.getString("SignCsrAction.ProblemOpeningCsr.Title"), problem);
        dProblem.setLocationRelativeTo(frame);
        dProblem.setVisible(true);

        return;
      }

      X509Certificate[] signingChain =
          X509CertUtil.orderX509CertChain(X509CertUtil.convertCertificates(certs));
      X509Certificate signingCert = signingChain[0];

      PublicKey publicKey = null;
      X500Name subject = null;
      DSignCsr dSignCsr = null;
      Provider provider = history.getExplicitProvider();

      if (pkcs10Csr != null) {
        publicKey = new JcaPKCS10CertificationRequest(pkcs10Csr).getPublicKey();
        subject = pkcs10Csr.getSubject();

        dSignCsr =
            new DSignCsr(frame, pkcs10Csr, csrFile, privateKey, keyPairType, signingCert, provider);
      } else {
        publicKey = spkacCsr.getPublicKey();
        subject = spkacCsr.getSubject().getName();

        dSignCsr =
            new DSignCsr(frame, spkacCsr, csrFile, privateKey, keyPairType, signingCert, provider);
      }

      dSignCsr.setLocationRelativeTo(frame);
      dSignCsr.setVisible(true);

      X509CertificateVersion version = dSignCsr.getVersion();
      SignatureType signatureType = dSignCsr.getSignatureType();
      long validityPeriod = dSignCsr.getValidityPeriod();
      BigInteger serialNumber = dSignCsr.getSerialNumber();
      caReplyFile = dSignCsr.getCaReplyFile();
      X509ExtensionSet extensions = dSignCsr.getExtensions();

      if (version == null) {
        return;
      }

      X500Name issuer =
          X500NameUtils.x500PrincipalToX500Name(signingCert.getSubjectX500Principal());

      // CA Reply is a cert with subject from CSR and issuer from signing cert's subject
      X509CertificateGenerator generator = new X509CertificateGenerator(version);
      X509Certificate caReplyCert =
          generator.generate(
              subject,
              issuer,
              validityPeriod,
              publicKey,
              privateKey,
              signatureType,
              serialNumber,
              extensions,
              provider);

      X509Certificate[] caReplyChain = new X509Certificate[signingChain.length + 1];

      caReplyChain[0] = caReplyCert;

      // Add all of the signing chain to the reply
      System.arraycopy(signingChain, 0, caReplyChain, 1, signingChain.length);

      byte[] caCertEncoded = X509CertUtil.getCertsEncodedPkcs7(caReplyChain);

      fos = new FileOutputStream(caReplyFile);
      fos.write(caCertEncoded);
    } catch (FileNotFoundException ex) {
      JOptionPane.showMessageDialog(
          frame,
          MessageFormat.format(res.getString("SignJarAction.NoWriteFile.message"), caReplyFile),
          res.getString("SignCsrAction.SignCsr.Title"),
          JOptionPane.WARNING_MESSAGE);
      return;
    } catch (Exception ex) {
      DError.displayError(frame, ex);
      return;
    } finally {
      IOUtils.closeQuietly(fos);
    }

    JOptionPane.showMessageDialog(
        frame,
        res.getString("SignCsrAction.SignCsrSuccessful.message"),
        res.getString("SignCsrAction.SignCsr.Title"),
        JOptionPane.INFORMATION_MESSAGE);
  }
Exemple #21
0
  public static java.lang.String initialize(
      java.lang.String s, java.lang.String s1, java.lang.String s2) {
    java.lang.String s3 = "";
    try {
      java.lang.System.setProperty(
          "java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
      java.security.Security.addProvider(new Provider());
      com.sun.net.ssl.SSLContext sslcontext = com.sun.net.ssl.SSLContext.getInstance("SSL");
      randomGenerator = new SecureRandom();
      byte abyte0[] = new byte[20];
      for (int i = 0; i < 20; i++) {
        abyte0[i] = (byte) (int) (java.lang.Math.random() * 256D - 128D);
      }

      randomGenerator.setSeed(abyte0);
      if ((new File(s + ".pfx")).exists()) {
        s = s + ".pfx";
      }
      com.sun.net.ssl.KeyManager akeymanager[] = null;
      try {
        if ((new File(s)).exists()) {
          java.security.KeyStore keystore;
          if (s.endsWith(".pfx")) {
            keystore = java.security.KeyStore.getInstance("PKCS12");
          } else {
            keystore = java.security.KeyStore.getInstance("JKS");
          }
          com.sun.net.ssl.KeyManagerFactory keymanagerfactory =
              com.sun.net.ssl.KeyManagerFactory.getInstance("SunX509");
          java.io.FileInputStream fileinputstream = new FileInputStream(s);
          char ac[] = s1.toCharArray();
          char ac1[] = s2.toCharArray();
          keystore.load(fileinputstream, ac);
          java.util.Enumeration enumeration = keystore.aliases();
          while (enumeration.hasMoreElements()) {
            java.lang.String s4 = (java.lang.String) enumeration.nextElement();
            certificateDescription = certificateDescription + " (" + s4;
            java.security.cert.Certificate acertificate[] = keystore.getCertificateChain(s4);
            if (acertificate != null) {
              int j = 0;
              while (j < acertificate.length) {
                java.security.cert.X509Certificate x509certificate =
                    (java.security.cert.X509Certificate) acertificate[j];
                certificateDescription =
                    certificateDescription
                        + " (cert "
                        + x509certificate.getSubjectDN()
                        + ", "
                        + x509certificate.getSigAlgName()
                        + ")";
                j++;
              }
            }
          }
          s3 = s3 + "certs: " + certificateDescription + "\n";
          keymanagerfactory.init(keystore, ac1);
          akeymanager = keymanagerfactory.getKeyManagers();
        }
      } catch (java.lang.Exception exception) {
        exception.printStackTrace();
        s3 = s3 + exception.toString();
      }
      sslcontext.init(akeymanager, null, randomGenerator);
      if (akeymanager != null) {
        sslServerSocketFactory = sslcontext.getServerSocketFactory();
      }
      sslSocketFactory = sslcontext.getSocketFactory();
    } catch (java.lang.Throwable throwable) {
      throwable.printStackTrace();
      s3 = s3 + throwable.toString();
    }
    return s3;
  }
  private String[] _getStrsAliasSourceToKpr(KeyStore kstOpenToSource) {
    String strMethod = "_getStrsAliasSourceToKpr(kstOpenToSource)";

    String[] strsAliasSourceAll = UtilKstAbs.s_getStrsAlias(super._frmOwner_, kstOpenToSource);

    if (strsAliasSourceAll == null) {
      MySystem.s_printOutError(this, strMethod, "nil strsAliasSourceAll");
      return null;
    }

    if (strsAliasSourceAll.length < 1) {
      MySystem.s_printOutWarning(this, strMethod, "strsAliasSourceAll.length < 1");

      String strBody = "No aliases found in " + UtilKstBks.f_s_strKeystoreType + " keystore:";

      strBody += "\n" + "  ";
      strBody += super._strPathAbsKstSource_;

      OPAbstract.s_showDialogWarning(super._frmOwner_, strBody);

      return null;
    }

    Vector<String> vec = new Vector<String>();

    try {
      for (int i = 0; i < strsAliasSourceAll.length; i++) {
        if (!kstOpenToSource.isKeyEntry(strsAliasSourceAll[i])) continue;

        Certificate[] certs = kstOpenToSource.getCertificateChain(strsAliasSourceAll[i]);

        if (certs == null) continue;

        if (certs.length < 1) continue;

        vec.addElement(strsAliasSourceAll[i]);
      }
    } catch (KeyStoreException excKeystore) {
      excKeystore.printStackTrace();
      MySystem.s_printOutError(this, strMethod, "excKeystore caught");

      // show dialog
      String strBody =
          "Got keystore Exception while reading " + UtilKstBks.f_s_strKeystoreType + " keystore:";

      strBody += "\n" + "  ";
      strBody += super._strPathAbsKstSource_;

      OPAbstract.s_showDialogWarning(super._frmOwner_, strBody);
    }

    // --

    if (vec.size() < 1) {
      MySystem.s_printOutWarning(this, strMethod, "vec.size() < 1");

      // show dialog
      String strBody =
          "No aliases pointing to keypair found in "
              + UtilKstBks.f_s_strKeystoreType
              + " keystore:";

      strBody += "\n" + "  ";
      strBody += super._strPathAbsKstSource_;

      OPAbstract.s_showDialogWarning(super._frmOwner_, strBody);

      return null;
    }

    // ---

    String[] strsAliasSourceToKpr = new String[vec.size()];

    for (int i = 0; i < vec.size(); i++) strsAliasSourceToKpr[i] = (String) vec.elementAt(i);

    return strsAliasSourceToKpr;
  }
Exemple #23
0
  private void readTest(String inKeyStore) throws Exception {

    KeyStore inputKeyStore;

    // Initialize KeyStore
    String dir = System.getProperty("test.src", ".");
    String keystorePath = dir + File.separator + "certs" + File.separator + "readP12";
    inputKeyStore = KeyStore.getInstance(IN_KEYSTORE_TYPE);
    // KeyStore have encoded by Base64.getMimeEncoder().encode(),need decode
    // first.
    byte[] input = Files.readAllBytes(Paths.get(keystorePath, inKeyStore));
    ByteArrayInputStream arrayIn = new ByteArrayInputStream(Base64.getMimeDecoder().decode(input));
    inputKeyStore.load(arrayIn, IN_STORE_PASS.toCharArray());
    out.println("Initialize KeyStore : " + inKeyStore + " success");

    out.println("getProvider : " + inputKeyStore.getProvider());
    out.println("getType : " + inputKeyStore.getType());
    out.println("getDefaultType : " + KeyStore.getDefaultType());

    int idx = 0;
    Enumeration<String> e = inputKeyStore.aliases();
    String alias;
    while (e.hasMoreElements()) {
      alias = e.nextElement();
      out.println("Alias " + idx + " : " + alias);
      if (inputKeyStore.containsAlias(alias) == false) {
        throw new RuntimeException("Alias not found");
      }

      out.println("getCreationDate : " + inputKeyStore.getCreationDate(alias));

      X509Certificate cert = (X509Certificate) inputKeyStore.getCertificate(alias);
      out.println("getCertificate : " + cert.getSubjectDN());
      String retAlias = inputKeyStore.getCertificateAlias(cert);
      if (!retAlias.equals(alias)) {
        throw new RuntimeException("Alias mismatch");
      }
      out.println("getCertificateAlias : " + retAlias);

      Certificate[] certs = inputKeyStore.getCertificateChain(alias);
      for (int i = 0; i < certs.length; i++) {
        out.println(
            "getCertificateChain " + i + " : " + ((X509Certificate) certs[i]).getSubjectDN());
      }

      boolean isCertEntry = inputKeyStore.isCertificateEntry(alias);
      // test KeyStore only contain key pair entries.
      if (isCertEntry == true) {
        throw new RuntimeException(
            "inputKeystore should not be certEntry because test keystore only contain key pair entries.");
      }

      boolean isKeyEntry = inputKeyStore.isKeyEntry(alias);
      if (isKeyEntry) {
        Key key = inputKeyStore.getKey(alias, IN_STORE_PASS.toCharArray());
        out.println("Key : " + key.toString());
      } else {
        throw new RuntimeException("Entry type unknown\n");
      }
      idx++;
    }

    int size = inputKeyStore.size();
    if (idx != size) {
      throw new RuntimeException("Size not match");
    }
  }
  public static TokenSearchResults searchTokenEntries(
      final KeyStore keyStore,
      final int startIndex,
      final int max,
      final QueryCriteria qc,
      final boolean includeData)
      throws CryptoTokenOfflineException, QueryException {
    final TokenSearchResults result;
    try {
      final ArrayList<TokenEntry> tokenEntries = new ArrayList<TokenEntry>();
      final Enumeration<String> e =
          keyStore
              .aliases(); // We assume the order is the same for every call unless entries has been
                          // added or removed

      final long maxIndex = (long) startIndex + max;
      for (int i = 0; i < maxIndex && e.hasMoreElements(); ) {
        final String keyAlias = e.nextElement();

        final String type;
        if (keyStore.entryInstanceOf(keyAlias, KeyStore.PrivateKeyEntry.class)) {
          type = TokenEntry.TYPE_PRIVATEKEY_ENTRY;
        } else if (keyStore.entryInstanceOf(keyAlias, KeyStore.SecretKeyEntry.class)) {
          type = TokenEntry.TYPE_SECRETKEY_ENTRY;
        } else if (keyStore.entryInstanceOf(keyAlias, KeyStore.TrustedCertificateEntry.class)) {
          type = TokenEntry.TYPE_TRUSTED_ENTRY;
        } else {
          type = null;
        }

        TokenEntry entry = new TokenEntry(keyAlias, type);

        if (shouldBeIncluded(entry, qc)) {
          if (i < startIndex) {
            i++;
            continue;
          }

          if (LOG.isDebugEnabled()) {
            LOG.debug("checking keyAlias: " + keyAlias);
          }

          // Add additional data
          if (includeData) {
            Map<String, String> info = new HashMap<String, String>();
            try {
              Date creationDate = keyStore.getCreationDate(keyAlias);
              entry.setCreationDate(creationDate);
            } catch (ProviderException ex) {
            } // NOPMD: We ignore if it is not supported

            if (TokenEntry.TYPE_PRIVATEKEY_ENTRY.equals(type)) {
              final Certificate[] chain = keyStore.getCertificateChain(keyAlias);
              if (chain.length > 0) {
                info.put(
                    INFO_KEY_ALGORITHM, AlgorithmTools.getKeyAlgorithm(chain[0].getPublicKey()));
                info.put(
                    INFO_KEY_SPECIFICATION,
                    AlgorithmTools.getKeySpecification(chain[0].getPublicKey()));
              }
              try {
                entry.setParsedChain(chain);
              } catch (CertificateEncodingException ex) {
                info.put("Error", ex.getMessage());
                LOG.error("Certificate could not be encoded for alias: " + keyAlias, ex);
              }
            } else if (TokenEntry.TYPE_TRUSTED_ENTRY.equals(type)) {
              Certificate certificate = keyStore.getCertificate(keyAlias);
              try {
                entry.setParsedTrustedCertificate(certificate);
              } catch (CertificateEncodingException ex) {
                info.put("Error", ex.getMessage());
                LOG.error("Certificate could not be encoded for alias: " + keyAlias, ex);
              }
            } else if (TokenEntry.TYPE_SECRETKEY_ENTRY.equals(type)) {
              try {
                KeyStore.Entry entry1 = keyStore.getEntry(keyAlias, null);
                SecretKey secretKey = ((KeyStore.SecretKeyEntry) entry1).getSecretKey();

                info.put(INFO_KEY_ALGORITHM, secretKey.getAlgorithm());
                // info.put(INFO_KEY_SPECIFICATION,
                // AlgorithmTools.getKeySpecification(chain[0].getPublicKey())); // TODO: Key
                // specification support for secret keys
              } catch (NoSuchAlgorithmException ex) {
                info.put("Error", ex.getMessage());
                LOG.error("Unable to get secret key for alias: " + keyAlias, ex);
              } catch (UnrecoverableEntryException ex) {
                info.put("Error", ex.getMessage());
                LOG.error("Unable to get secret key for alias: " + keyAlias, ex);
              }
            }
            entry.setInfo(info);
          }
          tokenEntries.add(entry);

          // Increase index
          i++;
        }
      }
      result = new TokenSearchResults(tokenEntries, e.hasMoreElements());
    } catch (KeyStoreException ex) {
      throw new CryptoTokenOfflineException(ex);
    }
    return result;
  }