/** java.security.KeyStore#size() */
  public void test_size() throws Exception {
    // Test for method int java.security.KeyStore.size()

    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.size();
      fail();
    } catch (KeyStoreException expected) {
    }

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

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

    // alias 3
    keyTest.setCertificateEntry("alias3", cert[1]);

    assertEquals("the size of the keyStore is not 3", 3, keyTest.size());
  }
Пример #2
0
  /**
   * Used to get the base ssl context in which to create the server socket. This is basically just
   * so we can have a custom location for key stores.
   */
  public SSLContext getSSLContext(String keyStoreName, String password) throws IOException {
    try {
      // Check the key manager factory
      KeyManagerFactory kmf = KeyManagerFactory.getInstance(this.keyManagerType);

      File ksFile = new File(keyStoreName);
      if (!ksFile.exists() || !ksFile.isFile())
        throw new WinstoneException(
            SSL_RESOURCES.getString("HttpsListener.KeyStoreNotFound", ksFile.getPath()));
      InputStream in = new FileInputStream(ksFile);
      char[] passwordChars = password == null ? null : password.toCharArray();
      KeyStore ks = KeyStore.getInstance("JKS");
      ks.load(in, passwordChars);
      kmf.init(ks, passwordChars);
      Logger.log(Logger.FULL_DEBUG, SSL_RESOURCES, "HttpsListener.KeyCount", ks.size() + "");
      for (Enumeration e = ks.aliases(); e.hasMoreElements(); ) {
        String alias = (String) e.nextElement();
        Logger.log(
            Logger.FULL_DEBUG,
            SSL_RESOURCES,
            "HttpsListener.KeyFound",
            new String[] {alias, ks.getCertificate(alias) + ""});
      }

      SSLContext context = SSLContext.getInstance("SSL");
      context.init(kmf.getKeyManagers(), null, null);
      Arrays.fill(passwordChars, 'x');
      return context;
    } catch (IOException err) {
      throw err;
    } catch (Throwable err) {
      throw new WinstoneException(
          SSL_RESOURCES.getString("HttpsListener.ErrorGettingContext"), err);
    }
  }
Пример #3
0
  /**
   * Writes out the details of all the key store entries. This makes for a long output. For
   * debugging purposes.
   */
  public void printKeyStoreContents() {
    try {
      String alias = null;
      KeyStore.TrustedCertificateEntry entry = null;

      for (Enumeration<String> aliases = keyStore.aliases(); aliases.hasMoreElements(); ) {
        alias = aliases.nextElement();
        System.out.println("");
        if (alias.startsWith(aliasPrefix)) {
          System.out.print(" * ===== ");
        } else {
          System.out.print("   ===== ");
        }
        System.out.println(alias);
        if (keyStore.isKeyEntry(alias)) {
          System.out.println("   is a KeyEntry                       (details hidden)");
          continue;
        } else if (keyStore.isCertificateEntry(alias)) {
          entry = (TrustedCertificateEntry) keyStore.getEntry(alias, null);
          System.out.println(entry.toString());
        }
        System.out.flush();
      } // end for

      System.out.println("");
      System.out.print("Number of entries in key store: ");
      System.out.println(keyStore.size());
      System.out.flush();

    } catch (Exception e) {
      System.err.println("ERROR: GFIPMKeystore.printKeyStoreContents failed: ");
      System.err.println(e.toString());
      System.err.flush();
    }
  } // end printKeyStoreContents
Пример #4
0
  public void checkServerTrusted(X509Certificate[] chain, String authType)
      throws CertificateException {
    if (ZimbraLog.security.isDebugEnabled()) {
      ZimbraLog.security.debug("Server certificate chain:");
      for (int i = 0; i < chain.length; ++i) {
        ZimbraLog.security.debug("X509Certificate[" + i + "]=" + chain[i]);
      }
    }

    try {
      getDefaultTrustManager().checkServerTrusted(chain, authType);
      return;
    } catch (CertificateException x) {
    }
    try {
      if (keyStore.size() == 0) throw new CertificateException("key store empty");
      getKeyStoreTrustManager().checkServerTrusted(chain, authType);
    } catch (CertificateException x) {
      String hostname =
          CustomSSLSocket
              .getCertificateHostname(); // stored as threadlocal if triggered from
                                         // CustomSSLSocketUtil
      if (hostname == null) hostname = SSLCertInfo.getCertificateCN(chain[0]);
      String certInfo = handleCertificateCheckFailure(hostname, chain[0], false);
      throw new CertificateException(certInfo);
    } catch (KeyStoreException x) {
      throw new CertificateException(x);
    }
  }
Пример #5
0
  /** Writes out the alias names of all the key store entries. For debugging purposes. */
  public void printKeyStoreAliases() {
    try {
      String alias = null;

      for (Enumeration<String> aliases = keyStore.aliases(); aliases.hasMoreElements(); ) {
        alias = aliases.nextElement();
        if (alias.startsWith(aliasPrefix)) {
          System.out.print(" * ");
        } else {
          System.out.print("   ");
        }
        System.out.println(alias);
      }

      System.out.println("");
      System.out.print("Number of entries in key store: ");
      System.out.println(keyStore.size());
      System.out.flush();

    } catch (KeyStoreException e) {
      System.err.println("ERROR: GFIPMKeystore.printKeyStoreAliases failed: ");
      System.err.println(e.toString());
      System.err.flush();
    }
  } // end printKeyStoreAliases
Пример #6
0
  @SuppressWarnings("unchecked")
  private static void printKeyStoreInfo(KeyStore keystore) throws KeyStoreException {
    log.debug("Provider : " + keystore.getProvider().getName());
    log.debug("Type : " + keystore.getType());
    log.debug("Size : " + keystore.size());

    Enumeration en = keystore.aliases();
    while (en.hasMoreElements()) {
      System.out.println("Alias: " + en.nextElement());
    }
  }
Пример #7
0
  private static TrustManager[] createTrustManagers() throws GeneralSecurityException, IOException {
    InputStream keyStoreStream =
        Thread.currentThread().getContextClassLoader().getResourceAsStream("ssltest-keystore.jks");
    char[] keyStorePassword = "******".toCharArray();
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(keyStoreStream, keyStorePassword);
    assert (ks.size() > 0);

    TrustManagerFactory tmf =
        TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(ks);
    return tmf.getTrustManagers();
  }
Пример #8
0
  /**
   * Writes out the certificates of all the key store entries. For debugging purposes.
   *
   * @param certformat If "rawcert", writes out the text information (long) about the certificates.
   *     If "enccert" [default], writes out the certificates in base64 (short).
   */
  public void printKeyStoreCertificates(String certformat) {
    try {
      String alias = null;
      Certificate cert;

      for (Enumeration<String> aliases = keyStore.aliases(); aliases.hasMoreElements(); ) {
        alias = aliases.nextElement();
        System.out.println("");
        if (alias.startsWith(aliasPrefix)) {
          System.out.print(" * ===== ");
        } else {
          System.out.print("   ===== ");
        }
        System.out.println(alias);
        // entry = (TrustedCertificateEntry) keyStore.getEntry(alias, null);
        System.out.print("   Creation Date:    ");
        System.out.println(keyStore.getCreationDate(alias));
        System.out.print("   Certificate type: ");
        cert = keyStore.getCertificate(alias);
        System.out.print(cert.getType());
        if (keyStore.isKeyEntry(alias)) {
          System.out.println("                          (details hidden)");
          continue;
        } else {
          System.out.println("");
        }

        if (keyStore.isCertificateEntry(alias)) {
          if ((certformat != null) && (certformat.equals("rawcert"))) {
            System.out.println(cert.toString());
          } else // enccert, encoded certificate
          {
            // String encoded = javax.xml.bind.DatatypeConverter.printBase64Binary(data);
            // byte[] decoded = javax.xml.bind.DatatypeConverter.parseBase64Binary(encoded);
            System.out.println(DatatypeConverter.printBase64Binary(cert.getEncoded()));
          }
        }
        System.out.flush();
      } // end for

      System.out.println("");
      System.out.print("Number of entries in key store: ");
      System.out.println(keyStore.size());
      System.out.flush();

    } catch (Exception e) {
      System.err.println("ERROR: GFIPMKeystore.printKeyStoreContents failed: ");
      System.err.println(e.toString());
      System.err.flush();
    }
  } // end printKeyStoreCertificates
Пример #9
0
  private static KeyManager[] createKeyManagers() throws GeneralSecurityException, IOException {
    InputStream keyStoreStream =
        Thread.currentThread().getContextClassLoader().getResourceAsStream("ssltest-cacerts.jks");
    char[] keyStorePassword = "******".toCharArray();
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(keyStoreStream, keyStorePassword);
    assert (ks.size() > 0);

    // Set up key manager factory to use our key store
    char[] certificatePassword = "******".toCharArray();
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
    kmf.init(ks, certificatePassword);

    // Initialize the SSLContext to work with our key managers.
    return kmf.getKeyManagers();
  }
  @GET
  @Produces({MediaType.APPLICATION_JSON})
  public Response getKeyList(@Context UriInfo uriInfo) throws Exception {
    List<SslKeyStoreEntry> result = new ArrayList<SslKeyStoreEntry>(keystore.size());

    Enumeration<String> e = keystore.aliases();
    while (e.hasMoreElements()) {
      String alias = e.nextElement();
      SslKeyStoreEntry sslKeyStoreEntry =
          DtoFactory.getInstance()
              .createDto(SslKeyStoreEntry.class)
              .withAlias(alias)
              .withType(keystore.isKeyEntry(alias) ? "Key" : "Certificate");
      result.add(sslKeyStoreEntry);
    }
    return Response.ok().entity(result).type(MediaType.APPLICATION_JSON).build();
  }
Пример #11
0
 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());
         }
       }
     }
   }
 }
Пример #12
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");
    }
  }