Java Code Examples for java.security.KeyStore#isCertificateEntry()

The following examples show how to use java.security.KeyStore#isCertificateEntry() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PKIXParameters.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates an instance of {@code PKIXParameters} that
 * populates the set of most-trusted CAs from the trusted
 * certificate entries contained in the specified {@code KeyStore}.
 * Only keystore entries that contain trusted {@code X509Certificates}
 * are considered; all other certificate types are ignored.
 *
 * @param keystore a {@code KeyStore} from which the set of
 * most-trusted CAs will be populated
 * @throws KeyStoreException if the keystore has not been initialized
 * @throws InvalidAlgorithmParameterException if the keystore does
 * not contain at least one trusted certificate entry
 * @throws NullPointerException if the keystore is {@code null}
 */
public PKIXParameters(KeyStore keystore)
    throws KeyStoreException, InvalidAlgorithmParameterException
{
    if (keystore == null)
        throw new NullPointerException("the keystore parameter must be " +
            "non-null");
    Set<TrustAnchor> hashSet = new HashSet<TrustAnchor>();
    Enumeration<String> aliases = keystore.aliases();
    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        if (keystore.isCertificateEntry(alias)) {
            Certificate cert = keystore.getCertificate(alias);
            if (cert instanceof X509Certificate)
                hashSet.add(new TrustAnchor((X509Certificate)cert, null));
        }
    }
    setTrustAnchors(hashSet);
    this.unmodInitialPolicies = Collections.<String>emptySet();
    this.certPathCheckers = new ArrayList<PKIXCertPathChecker>();
    this.certStores = new ArrayList<CertStore>();
}
 
Example 2
Source File: PKIXParameters.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates an instance of {@code PKIXParameters} that
 * populates the set of most-trusted CAs from the trusted
 * certificate entries contained in the specified {@code KeyStore}.
 * Only keystore entries that contain trusted {@code X509Certificates}
 * are considered; all other certificate types are ignored.
 *
 * @param keystore a {@code KeyStore} from which the set of
 * most-trusted CAs will be populated
 * @throws KeyStoreException if the keystore has not been initialized
 * @throws InvalidAlgorithmParameterException if the keystore does
 * not contain at least one trusted certificate entry
 * @throws NullPointerException if the keystore is {@code null}
 */
public PKIXParameters(KeyStore keystore)
    throws KeyStoreException, InvalidAlgorithmParameterException
{
    if (keystore == null)
        throw new NullPointerException("the keystore parameter must be " +
            "non-null");
    Set<TrustAnchor> hashSet = new HashSet<TrustAnchor>();
    Enumeration<String> aliases = keystore.aliases();
    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        if (keystore.isCertificateEntry(alias)) {
            Certificate cert = keystore.getCertificate(alias);
            if (cert instanceof X509Certificate)
                hashSet.add(new TrustAnchor((X509Certificate)cert, null));
        }
    }
    setTrustAnchors(hashSet);
    this.unmodInitialPolicies = Collections.<String>emptySet();
    this.certPathCheckers = new ArrayList<PKIXCertPathChecker>();
    this.certStores = new ArrayList<CertStore>();
}
 
Example 3
Source File: PKIXParameters.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates an instance of {@code PKIXParameters} that
 * populates the set of most-trusted CAs from the trusted
 * certificate entries contained in the specified {@code KeyStore}.
 * Only keystore entries that contain trusted {@code X509Certificates}
 * are considered; all other certificate types are ignored.
 *
 * @param keystore a {@code KeyStore} from which the set of
 * most-trusted CAs will be populated
 * @throws KeyStoreException if the keystore has not been initialized
 * @throws InvalidAlgorithmParameterException if the keystore does
 * not contain at least one trusted certificate entry
 * @throws NullPointerException if the keystore is {@code null}
 */
public PKIXParameters(KeyStore keystore)
    throws KeyStoreException, InvalidAlgorithmParameterException
{
    if (keystore == null)
        throw new NullPointerException("the keystore parameter must be " +
            "non-null");
    Set<TrustAnchor> hashSet = new HashSet<TrustAnchor>();
    Enumeration<String> aliases = keystore.aliases();
    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        if (keystore.isCertificateEntry(alias)) {
            Certificate cert = keystore.getCertificate(alias);
            if (cert instanceof X509Certificate)
                hashSet.add(new TrustAnchor((X509Certificate)cert, null));
        }
    }
    setTrustAnchors(hashSet);
    this.unmodInitialPolicies = Collections.<String>emptySet();
    this.certPathCheckers = new ArrayList<PKIXCertPathChecker>();
    this.certStores = new ArrayList<CertStore>();
}
 
Example 4
Source File: PKIXParameters.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an instance of {@code PKIXParameters} that
 * populates the set of most-trusted CAs from the trusted
 * certificate entries contained in the specified {@code KeyStore}.
 * Only keystore entries that contain trusted {@code X509Certificates}
 * are considered; all other certificate types are ignored.
 *
 * @param keystore a {@code KeyStore} from which the set of
 * most-trusted CAs will be populated
 * @throws KeyStoreException if the keystore has not been initialized
 * @throws InvalidAlgorithmParameterException if the keystore does
 * not contain at least one trusted certificate entry
 * @throws NullPointerException if the keystore is {@code null}
 */
public PKIXParameters(KeyStore keystore)
    throws KeyStoreException, InvalidAlgorithmParameterException
{
    if (keystore == null)
        throw new NullPointerException("the keystore parameter must be " +
            "non-null");
    Set<TrustAnchor> hashSet = new HashSet<TrustAnchor>();
    Enumeration<String> aliases = keystore.aliases();
    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        if (keystore.isCertificateEntry(alias)) {
            Certificate cert = keystore.getCertificate(alias);
            if (cert instanceof X509Certificate)
                hashSet.add(new TrustAnchor((X509Certificate)cert, null));
        }
    }
    setTrustAnchors(hashSet);
    this.unmodInitialPolicies = Collections.<String>emptySet();
    this.certPathCheckers = new ArrayList<PKIXCertPathChecker>();
    this.certStores = new ArrayList<CertStore>();
}
 
Example 5
Source File: PKIXParameters.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates an instance of {@code PKIXParameters} that
 * populates the set of most-trusted CAs from the trusted
 * certificate entries contained in the specified {@code KeyStore}.
 * Only keystore entries that contain trusted {@code X509Certificates}
 * are considered; all other certificate types are ignored.
 *
 * @param keystore a {@code KeyStore} from which the set of
 * most-trusted CAs will be populated
 * @throws KeyStoreException if the keystore has not been initialized
 * @throws InvalidAlgorithmParameterException if the keystore does
 * not contain at least one trusted certificate entry
 * @throws NullPointerException if the keystore is {@code null}
 */
public PKIXParameters(KeyStore keystore)
    throws KeyStoreException, InvalidAlgorithmParameterException
{
    if (keystore == null)
        throw new NullPointerException("the keystore parameter must be " +
            "non-null");
    Set<TrustAnchor> hashSet = new HashSet<TrustAnchor>();
    Enumeration<String> aliases = keystore.aliases();
    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        if (keystore.isCertificateEntry(alias)) {
            Certificate cert = keystore.getCertificate(alias);
            if (cert instanceof X509Certificate)
                hashSet.add(new TrustAnchor((X509Certificate)cert, null));
        }
    }
    setTrustAnchors(hashSet);
    this.unmodInitialPolicies = Collections.<String>emptySet();
    this.certPathCheckers = new ArrayList<PKIXCertPathChecker>();
    this.certStores = new ArrayList<CertStore>();
}
 
Example 6
Source File: PKIXParameters.java    From JDKSourceCode1.8 with MIT License 6 votes vote down vote up
/**
 * Creates an instance of {@code PKIXParameters} that
 * populates the set of most-trusted CAs from the trusted
 * certificate entries contained in the specified {@code KeyStore}.
 * Only keystore entries that contain trusted {@code X509Certificates}
 * are considered; all other certificate types are ignored.
 *
 * @param keystore a {@code KeyStore} from which the set of
 * most-trusted CAs will be populated
 * @throws KeyStoreException if the keystore has not been initialized
 * @throws InvalidAlgorithmParameterException if the keystore does
 * not contain at least one trusted certificate entry
 * @throws NullPointerException if the keystore is {@code null}
 */
public PKIXParameters(KeyStore keystore)
    throws KeyStoreException, InvalidAlgorithmParameterException
{
    if (keystore == null)
        throw new NullPointerException("the keystore parameter must be " +
            "non-null");
    Set<TrustAnchor> hashSet = new HashSet<TrustAnchor>();
    Enumeration<String> aliases = keystore.aliases();
    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        if (keystore.isCertificateEntry(alias)) {
            Certificate cert = keystore.getCertificate(alias);
            if (cert instanceof X509Certificate)
                hashSet.add(new TrustAnchor((X509Certificate)cert, null));
        }
    }
    setTrustAnchors(hashSet);
    this.unmodInitialPolicies = Collections.<String>emptySet();
    this.certPathCheckers = new ArrayList<PKIXCertPathChecker>();
    this.certStores = new ArrayList<CertStore>();
}
 
Example 7
Source File: X509CertUtil.java    From portecle with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Check whether or not a trusted certificate in the supplied keystore matches the the supplied X.509 certificate.
 *
 * @return The alias of the matching certificate in the keystore or null if there is no match
 * @param cert The certificate
 * @param keyStore The keystore
 * @throws CryptoException If there is a problem establishing trust
 */
public static String matchCertificate(KeyStore keyStore, X509Certificate cert)
    throws CryptoException
{
	try
	{
		for (Enumeration<String> en = keyStore.aliases(); en.hasMoreElements();)
		{
			String sAlias = en.nextElement();
			if (keyStore.isCertificateEntry(sAlias))
			{
				X509Certificate compCert = X509CertUtil.convertCertificate(keyStore.getCertificate(sAlias));

				if (cert.equals(compCert))
				{
					return sAlias;
				}
			}
		}
		return null;
	}
	catch (KeyStoreException ex)
	{
		throw new CryptoException(RB.getString("NoMatchCertificate.exception.message"), ex);
	}
}
 
Example 8
Source File: PKIXParameters.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates an instance of {@code PKIXParameters} that
 * populates the set of most-trusted CAs from the trusted
 * certificate entries contained in the specified {@code KeyStore}.
 * Only keystore entries that contain trusted {@code X509Certificates}
 * are considered; all other certificate types are ignored.
 *
 * @param keystore a {@code KeyStore} from which the set of
 * most-trusted CAs will be populated
 * @throws KeyStoreException if the keystore has not been initialized
 * @throws InvalidAlgorithmParameterException if the keystore does
 * not contain at least one trusted certificate entry
 * @throws NullPointerException if the keystore is {@code null}
 */
public PKIXParameters(KeyStore keystore)
    throws KeyStoreException, InvalidAlgorithmParameterException
{
    if (keystore == null)
        throw new NullPointerException("the keystore parameter must be " +
            "non-null");
    Set<TrustAnchor> hashSet = new HashSet<TrustAnchor>();
    Enumeration<String> aliases = keystore.aliases();
    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        if (keystore.isCertificateEntry(alias)) {
            Certificate cert = keystore.getCertificate(alias);
            if (cert instanceof X509Certificate)
                hashSet.add(new TrustAnchor((X509Certificate)cert, null));
        }
    }
    setTrustAnchors(hashSet);
    this.unmodInitialPolicies = Collections.<String>emptySet();
    this.certPathCheckers = new ArrayList<PKIXCertPathChecker>();
    this.certStores = new ArrayList<CertStore>();
}
 
Example 9
Source File: TestSSLContext.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public static void assertCertificateInKeyStore(Certificate certificate,
                                               KeyStore keyStore) throws Exception {
    boolean found = false;
    for (String alias: Collections.list(keyStore.aliases())) {
        if (!keyStore.isCertificateEntry(alias)) {
            continue;
        }
        Certificate keyStoreCertificate = keyStore.getCertificate(alias);
        if (certificate.equals(keyStoreCertificate)) {
            found = true;
            break;
        }
    }
    assertTrue(found);
}
 
Example 10
Source File: FtpsClient.java    From ats-framework with Apache License 2.0 5 votes vote down vote up
public DefaultTrustStrategy( KeyStore trustStore ) throws Exception {
    /** get all certificates from the trust store **/
    Enumeration<String> aliases = trustStore.aliases();
    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        if (trustStore.isCertificateEntry(alias)) {
            /** the alias points to a certificate **/
            certificates.add(trustStore.getCertificate(alias));
        } else {
            /** the alias does not point to a certificate, 
             * but this may mean that it points to a private-public key pair or a certificate chain 
             */
            Certificate certificate = trustStore.getCertificate(alias);
            if (certificate != null) {
                /**
                 * the certificate was extracted from a private-public key entry
                 * */
                certificates.add(certificate);
            } else {
                /**
                 * the alias points to a certificate chain
                 * */
                Certificate[] chain = trustStore.getCertificateChain(alias);
                for (Certificate cert : chain) {
                    certificates.add(cert);
                }
            }
        }
    }
}
 
Example 11
Source File: KeyStoreManagement.java    From cougar with Apache License 2.0 5 votes vote down vote up
private KeyStoreManagement(KeyStore keyStore, Resource source, String type) throws KeyStoreException {
    this.keyStore = keyStore;
    this.source = source;
    this.type = type;
    Enumeration<String> aliases = keyStore.aliases();
    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();

        if (keyStore.isCertificateEntry(alias)) {
            addCertificate(alias);
        } else {
            addCertificateChain(alias);
        }
    }
}
 
Example 12
Source File: WriteP12Test.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
private void testKeyStore(KeyStore inputKeyStore, char[] keypass)
        throws KeyStoreException, UnrecoverableKeyException,
        NoSuchAlgorithmException {
    out.println("========== Key Store ==========");
    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();
        if (!inputKeyStore.containsAlias(alias)) {
            throw new RuntimeException("Alias not found");
        }
        out.println("Alias " + idx + " : " + alias);
        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, actually "
                    + retAlias + ", expected " + alias);
        }
        out.println("getCertificateAlias : " + retAlias);
        Certificate[] certs = inputKeyStore.getCertificateChain(alias);
        int i = 0;
        for (Certificate certification : certs) {
            out.println("getCertificateChain " + i
                    + ((X509Certificate) certification).getSubjectDN());
            i++;
        }
        if (inputKeyStore.isCertificateEntry(alias)) {
            throw new RuntimeException(
                    "inputKeystore should not be certEntry because this"
                            + " keystore only contain key pair entries.");
        }
        if (!inputKeyStore.isKeyEntry(alias)) {
            throw new RuntimeException("Entry type unknown.");
        }
        idx++;
    }
    int size = inputKeyStore.size();
    if (idx != size) {
        throw new RuntimeException("Size not match, actually " + idx
                + ", expected " + size);
    }
}
 
Example 13
Source File: TestKeyStoreEntry.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
public void runTest(Provider p) throws Exception {
    try (FileOutputStream fos = new FileOutputStream("jceks");
            FileInputStream fis = new FileInputStream("jceks");) {

        KeyStore ks = KeyStore.getInstance("jceks", p);
        // create an empty key store
        ks.load(null, null);

        // store the secret keys
        String aliasHead = new String("secretKey");
        for (int j = 0; j < NUM_ALGOS; j++) {
            ks.setKeyEntry(aliasHead + j, sks[j], PASSWDK, null);
        }

        // write the key store out to a file
        ks.store(fos, PASSWDF);
        // wipe clean the existing key store
        for (int k = 0; k < NUM_ALGOS; k++) {
            ks.deleteEntry(aliasHead + k);
        }
        if (ks.size() != 0) {
            throw new RuntimeException("ERROR: re-initialization failed");
        }

        // reload the key store with the file
        ks.load(fis, PASSWDF);

        // check the integrity/validaty of the key store
        Key temp = null;
        String alias = null;
        if (ks.size() != NUM_ALGOS) {
            throw new RuntimeException("ERROR: wrong number of key"
                    + " entries");
        }

        for (int m = 0; m < ks.size(); m++) {
            alias = aliasHead + m;
            temp = ks.getKey(alias, PASSWDK);
            // compare the keys
            if (!temp.equals(sks[m])) {
                throw new RuntimeException("ERROR: key comparison (" + m
                        + ") failed");
            }
            // check the type of key
            if (ks.isCertificateEntry(alias) || !ks.isKeyEntry(alias)) {
                throw new RuntimeException("ERROR: type identification ("
                        + m + ") failed");
            }
        }
    }
}
 
Example 14
Source File: DKSTest.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    /*
     * domain keystore: system
     */
    URI config = new URI(CONFIG + "#system");
    int cacertsCount;
    int expected;
    KeyStore keystore = KeyStore.getInstance("DKS");
    // load entries
    keystore.load(new DomainLoadStoreParameter(config, PASSWORDS));
    cacertsCount = expected = keystore.size();
    System.out.println("\nLoading domain keystore: " + config + "\t[" +
        expected + " entries]");
    checkEntries(keystore, expected);

    /*
     * domain keystore: system_plus
     */
    config = new URI(CONFIG + "#system_plus");
    expected = cacertsCount + 1;
    keystore = KeyStore.getInstance("DKS");
    // load entries
    keystore.load(new DomainLoadStoreParameter(config, PASSWORDS));
    System.out.println("\nLoading domain keystore: " + config + "\t[" +
        expected + " entries]");
    checkEntries(keystore, expected);

    /*
     * domain keystore: system_env
     */
    config = new URI(CONFIG + "#system_env");
    expected = 1 + cacertsCount;
    keystore = KeyStore.getInstance("DKS");
    // load entries
    keystore.load(
        new DomainLoadStoreParameter(config,
            Collections.<String, KeyStore.ProtectionParameter>emptyMap()));
    System.out.println("\nLoading domain keystore: " + config + "\t[" +
        expected + " entries]");
    checkEntries(keystore, expected);

    /*
     * domain keystore: empty
     */
    KeyStore empty = KeyStore.getInstance("JKS");
    empty.load(null, null);

    try (OutputStream outStream =
        new FileOutputStream(new File(USER_DIR, "empty.jks"))) {
        empty.store(outStream, "passphrase".toCharArray());
    }
    config = new URI(CONFIG + "#empty");
    expected = 0;
    keystore = KeyStore.getInstance("DKS");
    // load entries
    keystore.load(new DomainLoadStoreParameter(config, PASSWORDS));
    System.out.println("\nLoading domain keystore: " + config + "\t[" +
        expected + " entries]");
    checkEntries(keystore, expected);

    /*
     * domain keystore: keystores
     */
    config = new URI(CONFIG + "#keystores");
    expected = 2 + 1 + 1 + 1;
    keystore = KeyStore.getInstance("DKS");
    // load entries
    keystore.load(new DomainLoadStoreParameter(config, PASSWORDS));
    System.out.println("\nLoading domain keystore: " + config + "\t[" +
        expected + " entries]");
    checkEntries(keystore, expected);
    // set a new trusted certificate entry
    Certificate cert = loadCertificate(CERT);
    String alias = "pw_keystore tmp-cert";
    System.out.println("Setting new trusted certificate entry: " + alias);
    keystore.setEntry(alias,
        new KeyStore.TrustedCertificateEntry(cert), null);
    expected++;
    // store entries
    config = new URI(CONFIG + "#keystores_tmp");
    System.out.println("Storing domain keystore: " + config + "\t[" +
        expected + " entries]");
    keystore.store(new DomainLoadStoreParameter(config, PASSWORDS));
    keystore = KeyStore.getInstance("DKS");
    // reload entries
    keystore.load(new DomainLoadStoreParameter(config, PASSWORDS));
    System.out.println("Reloading domain keystore: " + config + "\t[" +
        expected + " entries]");
    checkEntries(keystore, expected);
    // get the new trusted certificate entry
    System.out.println("Getting new trusted certificate entry: " + alias);
    if (!keystore.isCertificateEntry(alias)) {
        throw new Exception("Error: cannot retrieve certificate entry: " +
            alias);
    }
    keystore.setEntry(alias,
        new KeyStore.TrustedCertificateEntry(cert), null);
}
 
Example 15
Source File: ReadP12Test.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
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_KETYSTORE_TYPE, IN_KEYSTORE_PRV);
        // 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");
        }

    }
 
Example 16
Source File: WriteP12Test.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
private void testKeyStore(KeyStore inputKeyStore, char[] keypass)
        throws KeyStoreException, UnrecoverableKeyException,
        NoSuchAlgorithmException {
    out.println("========== Key Store ==========");
    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();
        if (!inputKeyStore.containsAlias(alias)) {
            throw new RuntimeException("Alias not found");
        }
        out.println("Alias " + idx + " : " + alias);
        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, actually "
                    + retAlias + ", expected " + alias);
        }
        out.println("getCertificateAlias : " + retAlias);
        Certificate[] certs = inputKeyStore.getCertificateChain(alias);
        int i = 0;
        for (Certificate certification : certs) {
            out.println("getCertificateChain " + i
                    + ((X509Certificate) certification).getSubjectDN());
            i++;
        }
        if (inputKeyStore.isCertificateEntry(alias)) {
            throw new RuntimeException(
                    "inputKeystore should not be certEntry because this"
                            + " keystore only contain key pair entries.");
        }
        if (!inputKeyStore.isKeyEntry(alias)) {
            throw new RuntimeException("Entry type unknown.");
        }
        idx++;
    }
    int size = inputKeyStore.size();
    if (idx != size) {
        throw new RuntimeException("Size not match, actually " + idx
                + ", expected " + size);
    }
}
 
Example 17
Source File: TestKeyStoreEntry.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
public void runTest(Provider p) throws Exception {
    try (FileOutputStream fos = new FileOutputStream("jceks");
            FileInputStream fis = new FileInputStream("jceks");) {

        KeyStore ks = KeyStore.getInstance("jceks", p);
        // create an empty key store
        ks.load(null, null);

        // store the secret keys
        String aliasHead = new String("secretKey");
        for (int j = 0; j < NUM_ALGOS; j++) {
            ks.setKeyEntry(aliasHead + j, sks[j], PASSWDK, null);
        }

        // write the key store out to a file
        ks.store(fos, PASSWDF);
        // wipe clean the existing key store
        for (int k = 0; k < NUM_ALGOS; k++) {
            ks.deleteEntry(aliasHead + k);
        }
        if (ks.size() != 0) {
            throw new RuntimeException("ERROR: re-initialization failed");
        }

        // reload the key store with the file
        ks.load(fis, PASSWDF);

        // check the integrity/validaty of the key store
        Key temp = null;
        String alias = null;
        if (ks.size() != NUM_ALGOS) {
            throw new RuntimeException("ERROR: wrong number of key"
                    + " entries");
        }

        for (int m = 0; m < ks.size(); m++) {
            alias = aliasHead + m;
            temp = ks.getKey(alias, PASSWDK);
            // compare the keys
            if (!temp.equals(sks[m])) {
                throw new RuntimeException("ERROR: key comparison (" + m
                        + ") failed");
            }
            // check the type of key
            if (ks.isCertificateEntry(alias) || !ks.isKeyEntry(alias)) {
                throw new RuntimeException("ERROR: type identification ("
                        + m + ") failed");
            }
        }
    }
}
 
Example 18
Source File: ReadP12Test.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
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_KETYSTORE_TYPE, IN_KEYSTORE_PRV);
        // 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");
        }

    }
 
Example 19
Source File: WriteP12Test.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
private void testKeyStore(KeyStore inputKeyStore, char[] keypass)
        throws KeyStoreException, UnrecoverableKeyException,
        NoSuchAlgorithmException {
    out.println("========== Key Store ==========");
    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();
        if (!inputKeyStore.containsAlias(alias)) {
            throw new RuntimeException("Alias not found");
        }
        out.println("Alias " + idx + " : " + alias);
        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, actually "
                    + retAlias + ", expected " + alias);
        }
        out.println("getCertificateAlias : " + retAlias);
        Certificate[] certs = inputKeyStore.getCertificateChain(alias);
        int i = 0;
        for (Certificate certification : certs) {
            out.println("getCertificateChain " + i
                    + ((X509Certificate) certification).getSubjectDN());
            i++;
        }
        if (inputKeyStore.isCertificateEntry(alias)) {
            throw new RuntimeException(
                    "inputKeystore should not be certEntry because this"
                            + " keystore only contain key pair entries.");
        }
        if (!inputKeyStore.isKeyEntry(alias)) {
            throw new RuntimeException("Entry type unknown.");
        }
        idx++;
    }
    int size = inputKeyStore.size();
    if (idx != size) {
        throw new RuntimeException("Size not match, actually " + idx
                + ", expected " + size);
    }
}
 
Example 20
Source File: KeyStoreUtil.java    From keystore-explorer with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Is the named entry in the KeyStore a trusted certificate entry?
 *
 * @param alias
 *            Alias
 * @param keyStore
 *            KeyStore
 * @return True if it is, false otherwise
 * @throws KeyStoreException
 *             If there was a problem accessing the KeyStore.
 */
public static boolean isTrustedCertificateEntry(String alias, KeyStore keyStore) throws KeyStoreException {
	return keyStore.isCertificateEntry(alias);
}