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

The following examples show how to use java.security.KeyStore#aliases() . 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: PdfPKCS7.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Verifies a timestamp against a KeyStore.
 * @param ts the timestamp
 * @param keystore the <CODE>KeyStore</CODE>
 * @param provider the provider or <CODE>null</CODE> to use the BouncyCastle provider
 * @return <CODE>true</CODE> is a certificate was found
 * @since	2.1.6
 */    
public static boolean verifyTimestampCertificates(TimeStampToken ts, KeyStore keystore, String provider) {
    if (provider == null)
        provider = "BC";
    try {
        for (Enumeration aliases = keystore.aliases(); aliases.hasMoreElements();) {
            try {
                String alias = (String)aliases.nextElement();
                if (!keystore.isCertificateEntry(alias))
                    continue;
                X509Certificate certStoreX509 = (X509Certificate)keystore.getCertificate(alias);
                SignerInformationVerifier siv = new JcaSimpleSignerInfoVerifierBuilder().setProvider(provider).build(certStoreX509);
                ts.validate(siv);
                return true;
            }
            catch (Exception ex) {
            }
        }
    }
    catch (Exception e) {
    }
    return false;
}
 
Example 2
Source File: PKIXParameters.java    From jdk8u60 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: Main.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Locates a signer for a given certificate from a given keystore and
 * returns the signer's certificate.
 * @param cert the certificate whose signer is searched, not null
 * @param ks the keystore to search with, not null
 * @return <code>cert</code> itself if it's already inside <code>ks</code>,
 * or a certificate inside <code>ks</code> who signs <code>cert</code>,
 * or null otherwise. A label is added.
 */
private static Pair<String,Certificate>
        getSigner(Certificate cert, KeyStore ks) throws Exception {
    if (ks.getCertificateAlias(cert) != null) {
        return new Pair<>("", cert);
    }
    for (Enumeration<String> aliases = ks.aliases();
            aliases.hasMoreElements(); ) {
        String name = aliases.nextElement();
        Certificate trustedCert = ks.getCertificate(name);
        if (trustedCert != null) {
            try {
                cert.verify(trustedCert.getPublicKey());
                return new Pair<>(name, trustedCert);
            } catch (Exception e) {
                // Not verified, skip to the next one
            }
        }
    }
    return null;
}
 
Example 4
Source File: TrustUtil.java    From AndroidHttpCapture with MIT License 6 votes vote down vote up
/**
 * Extracts the {@link java.security.KeyStore.TrustedCertificateEntry}s from the specified KeyStore. All other entry
 * types, including private keys, will be ignored.
 *
 * @param trustStore keystore containing trusted certificate entries
 * @return the trusted certificate entries in the specified keystore
 */
public static List<X509Certificate> extractTrustedCertificateEntries(KeyStore trustStore) {
    try {
        Enumeration<String> aliases = trustStore.aliases();
        List<String> keyStoreAliases = Collections.list(aliases);

        List<X509Certificate> trustedCertificates = new ArrayList<>(keyStoreAliases.size());

        for (String alias : keyStoreAliases) {
            if (trustStore.entryInstanceOf(alias, KeyStore.TrustedCertificateEntry.class)) {
                Certificate certificate = trustStore.getCertificate(alias);
                if (!(certificate instanceof X509Certificate)) {
                    log.debug("Skipping non-X509Certificate in KeyStore. Certificate type: {}", certificate.getType());
                    continue;
                }

                trustedCertificates.add((X509Certificate) certificate);
            }
        }

        return trustedCertificates;
    } catch (KeyStoreException e) {
        throw new KeyStoreAccessException("Error occurred while retrieving trusted CAs from KeyStore", e);
    }
}
 
Example 5
Source File: Main.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
/**
 * Locates a signer for a given certificate from a given keystore and
 * returns the signer's certificate.
 * @param cert the certificate whose signer is searched, not null
 * @param ks the keystore to search with, not null
 * @return <code>cert</code> itself if it's already inside <code>ks</code>,
 * or a certificate inside <code>ks</code> who signs <code>cert</code>,
 * or null otherwise. A label is added.
 */
private static Pair<String,Certificate>
        getSigner(Certificate cert, KeyStore ks) throws Exception {
    if (ks.getCertificateAlias(cert) != null) {
        return new Pair<>("", cert);
    }
    for (Enumeration<String> aliases = ks.aliases();
            aliases.hasMoreElements(); ) {
        String name = aliases.nextElement();
        Certificate trustedCert = ks.getCertificate(name);
        if (trustedCert != null) {
            try {
                cert.verify(trustedCert.getPublicKey());
                return new Pair<>(name, trustedCert);
            } catch (Exception e) {
                // Not verified, skip to the next one
            }
        }
    }
    return null;
}
 
Example 6
Source File: PKIXParameters.java    From jdk-1.7-annotated with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an instance of <code>PKIXParameters</code> that
 * populates the set of most-trusted CAs from the trusted
 * certificate entries contained in the specified <code>KeyStore</code>.
 * Only keystore entries that contain trusted <code>X509Certificates</code>
 * are considered; all other certificate types are ignored.
 *
 * @param keystore a <code>KeyStore</code> 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</code>
 */
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: KeyStoreAdminClient.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
public boolean isPrivateKeyStore(byte[] content, String password, String type)
        throws java.lang.Exception {
    try {
        boolean isPrivateStore = false;
        ByteArrayInputStream stream = new ByteArrayInputStream(content);
        KeyStore store = KeyStore.getInstance(type);
        store.load(stream, password.toCharArray());
        Enumeration<String> aliases = store.aliases();
        while (aliases.hasMoreElements()) {
            String value = aliases.nextElement();
            if (store.isKeyEntry(value)) {
                isPrivateStore = true;
                break;
            }
        }
        return isPrivateStore;
    } catch (java.lang.Exception e) {
        log.error("Error in checking private key store.", e);
        throw e;
    }
}
 
Example 8
Source File: ClientCertificateTest.java    From davmail with GNU General Public License v2.0 6 votes vote down vote up
public void testWindowsSmartCard() {
    try {
        KeyStore ks = KeyStore.getInstance("Windows-MY");
        ks.load(null, null);
        java.util.Enumeration<String> en = ks.aliases();

        while (en.hasMoreElements()) {
            String aliasKey = en.nextElement();
            X509Certificate c = (X509Certificate) ks.getCertificate(aliasKey);
            System.out.println("---> alias : " + aliasKey + " " + c.getSubjectDN());

            //PrivateKey key = (PrivateKey) ks.getKey(aliasKey, "Passw0rd".toCharArray());
            Certificate[] chain = ks.getCertificateChain(aliasKey);
            System.out.println(Arrays.asList(chain));
        }

    } catch (Exception ioe) {
        System.err.println(ioe.getMessage());
    }
}
 
Example 9
Source File: CertificateUtil.java    From android-testdpc with Apache License 2.0 6 votes vote down vote up
/**
 * By enumerating the entries in a pkcs12 cert, find out the first entry that contain both
 * private key and certificate.
 *
 * @param contentResolver
 * @param uri uri of pkcs12 cert
 * @param password cert password
 * @return {@link PKCS12ParseInfo} which contains alias, x509 cert and private key, null if
 *         no such an entry.
 * @throws KeyStoreException
 * @throws NoSuchAlgorithmException
 * @throws IOException
 * @throws CertificateException
 * @throws UnrecoverableKeyException
 */
public static PKCS12ParseInfo parsePKCS12Certificate(
        ContentResolver contentResolver, Uri uri, String password)
        throws KeyStoreException, NoSuchAlgorithmException, IOException, CertificateException,
        UnrecoverableKeyException {
    InputStream inputStream = contentResolver.openInputStream(uri);
    KeyStore keystore = KeyStore.getInstance("PKCS12");
    keystore.load(inputStream, password.toCharArray());
    Enumeration<String> aliases = keystore.aliases();
    // Find an entry contains both private key and user cert.
    for (String alias : Collections.list(aliases)) {
        PrivateKey privateKey = (PrivateKey) keystore.getKey(alias, "".toCharArray());
        if (privateKey == null) {
            continue;
        }
        X509Certificate clientCertificate =
                (X509Certificate) keystore.getCertificate(alias);
        if (clientCertificate == null) {
            continue;
        }
        Log.d(TAG, "parsePKCS12Certificate: " + alias + " is selected");
        return new PKCS12ParseInfo(alias, clientCertificate, privateKey);
    }
    return null;
}
 
Example 10
Source File: IterateWindowsRootStore.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // Try to register a JCE provider from property sun.security.mscapi.testprovider in the first slot
    // otherwise register a dummy provider which would provoke the issue of bug 8139436
    boolean providerPrepended = false;
    String testprovider = System.getProperty("sun.security.mscapi.testprovider");
    if (testprovider != null && !testprovider.isEmpty()) {
        try {
            System.out.println("Trying to prepend external JCE provider " + testprovider);
            Class<?> providerclass = Class.forName(testprovider);
            Object provider = providerclass.newInstance();
            Security.insertProviderAt((Provider)provider, 1);
        } catch (Exception e) {
            System.out.println("Could not load JCE provider " + testprovider +". Exception is:");
            e.printStackTrace(System.out);
        }
        providerPrepended = true;
        System.out.println("Sucessfully prepended JCE provider " + testprovider);
    }
    if (!providerPrepended) {
        System.out.println("Trying to prepend dummy JCE provider");
        Security.insertProviderAt(new TestProvider(), 1);
        System.out.println("Sucessfully prepended dummy JCE provider");
    }

    // load Windows-ROOT KeyStore
    KeyStore keyStore = KeyStore.getInstance("Windows-ROOT", "SunMSCAPI");
    keyStore.load(null, null);

    // iterate KeyStore
    Enumeration<String> aliases = keyStore.aliases();
    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        System.out.print("Reading certificate for alias: " + alias + "...");
        keyStore.getCertificate(alias);
        System.out.println(" done.");
    }
}
 
Example 11
Source File: KeyStoreReaderImpl.java    From java-certificate-authority with Apache License 2.0 5 votes vote down vote up
@Override
public List<String> listAliases(KeyStore keyStore) {
  final List<String> res = new ArrayList<>();
  try {
    for (final Enumeration<String> aliases = keyStore.aliases(); aliases.hasMoreElements();) {
      res.add(aliases.nextElement());
    }
    return res;
  } catch (final KeyStoreException e) {
    throw new CaException(e);
  }

}
 
Example 12
Source File: KeyStoreTest.java    From athenz with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateKeyStore() throws Exception {
    KeyStore keyStore = Utils.createKeyStore("rsa_public_x509.cert", "unit_test_rsa_private.key");
    assertNotNull(keyStore);
    String alias = null;
    for (Enumeration<?> e = keyStore.aliases(); e.hasMoreElements(); ) {
        alias = (String) e.nextElement();
        assertEquals(ALIAS_NAME, alias);
    }
    X509Certificate[] chain = (X509Certificate[]) keyStore.getCertificateChain(alias);
    assertNotNull(chain);
    assertTrue(chain.length == 1);
}
 
Example 13
Source File: KeyStoreResolver.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Constructor KeyStoreResolver
 *
 * @param keyStore is the keystore which contains the Certificates
 * @throws StorageResolverException
 */
public KeyStoreResolver(KeyStore keyStore) throws StorageResolverException {
    this.keyStore = keyStore;
    // Do a quick check on the keystore
    try {
        keyStore.aliases();
    } catch (KeyStoreException ex) {
        throw new StorageResolverException("generic.EmptyMessage", ex);
    }
}
 
Example 14
Source File: KeyManagerUtils.java    From Aria with Apache License 2.0 5 votes vote down vote up
private static String findAlias(KeyStore ks) throws KeyStoreException {
  Enumeration<String> e = ks.aliases();
  while (e.hasMoreElements()) {
    String entry = e.nextElement();
    if (ks.isKeyEntry(entry)) {
      return entry;
    }
  }
  throw new KeyStoreException("Cannot find a private key entry");
}
 
Example 15
Source File: KeyStoreResolver.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Constructor KeyStoreResolver
 *
 * @param keyStore is the keystore which contains the Certificates
 * @throws StorageResolverException
 */
public KeyStoreResolver(KeyStore keyStore) throws StorageResolverException {
    this.keyStore = keyStore;
    // Do a quick check on the keystore
    try {
        keyStore.aliases();
    } catch (KeyStoreException ex) {
        throw new StorageResolverException("generic.EmptyMessage", ex);
    }
}
 
Example 16
Source File: ClientKey.java    From eet-client with MIT License 5 votes vote down vote up
private Enumeration<String> getAliases(final KeyStore keystore) throws InvalidKeystoreException {
    try {
        return keystore.aliases();
    } catch (final KeyStoreException e) {
        throw new InvalidKeystoreException(e);
    }
}
 
Example 17
Source File: ConsumerEndpoint.java    From MaxKey with Apache License 2.0 4 votes vote down vote up
/**
 * 初始化sp证书
 * 
 * @throws Exception
 */
private void initCredential(String spId) throws Exception {
	// 1. 获取 sp keyStore
	AppsSAML20Details saml20Details = saml20DetailsService.get(spId);
	if (saml20Details == null) {
		// TODO
		logger.error("spid[" + spId + "] not exists");
		throw new Exception();
	}
	byte[] keyStoreBytes = saml20Details.getKeyStore();
	InputStream keyStoreStream = new ByteArrayInputStream(keyStoreBytes);

	try {
		KeyStore keyStore = KeyStore.getInstance(keyStoreLoader.getKeystoreType());
		keyStore.load(keyStoreStream, keyStoreLoader.getKeystorePassword().toCharArray());

		Map<String, String> passwords = new HashMap<String, String>();
		for (Enumeration<String> en = keyStore.aliases(); en.hasMoreElements();) {
			String aliase = en.nextElement();
			if (aliase.equalsIgnoreCase(keyStoreLoader.getEntityName())) {
				passwords.put(aliase, keyStoreLoader.getKeystorePassword());
			}
		}
		// TrustResolver trustResolver = new
		// TrustResolver(keyStore,keyStoreLoader.getIdpIssuingEntityName(),keyStoreLoader.getKeystorePassword());

		AuthnResponseGenerator authnResponseGenerator = new AuthnResponseGenerator(
				keyStoreLoader.getEntityName(), timeService,
				idService);
		// endpointGenerator = new EndpointGenerator();

		CriteriaSet criteriaSet = new CriteriaSet();
		criteriaSet.add(new EntityIDCriteria(keyStoreLoader
				.getEntityName()));
		criteriaSet.add(new UsageCriteria(UsageType.SIGNING));

		KeyStoreCredentialResolver credentialResolver = new KeyStoreCredentialResolver(
				keyStore, passwords);
		signingCredential = credentialResolver.resolveSingle(criteriaSet);
		Validate.notNull(signingCredential);

		// adapter set resolver
		TrustResolver trustResolver = new TrustResolver(keyStore,
				keyStoreLoader.getEntityName(),
				keyStoreLoader.getKeystorePassword(), issueInstantRule,
				messageReplayRule,"POST");
		extractBindingAdapter.setSecurityPolicyResolver(trustResolver
				.getStaticSecurityPolicyResolver());
	} catch (Exception e) {
		logger.error("初始化sp证书出错");
		throw new Exception(e);
	}
}
 
Example 18
Source File: KeystoreLongTest.java    From SPDS with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void test2() throws KeyStoreException {
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.aliases();
    mustBeInErrorState(ks);
}
 
Example 19
Source File: ReadP12Test.java    From jdk8u-jdk 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 20
Source File: SSLClientCertificatesMSCapi.java    From APICloud-Studio with GNU General Public License v3.0 4 votes vote down vote up
/**
    *
 * @param parent
    * @param url : the url from which we want to get the root url
 */

public SSLClientCertificatesMSCapi(Shell parent, String realm) {
	super(parent);
	// List<String[]> list = new ArrayList<String[]>();
	List list = new ArrayList();
	Provider pmscapi = Security.getProvider("SunMSCAPI"); //$NON-NLS-1$
	Provider pjacapi = Security.getProvider("CAPI"); //$NON-NLS-1$
	try {
		KeyStore keyStore = null;
		//use JACAPI
		if (pmscapi != null) {
			keyStore = KeyStore.getInstance("Windows-MY",pmscapi); //$NON-NLS-1$
			pmscapi.setProperty("Signature.SHA1withRSA","sun.security.mscapi.RSASignature$SHA1"); //$NON-NLS-1$ //$NON-NLS-2$
		} else if (pjacapi != null) {
			keyStore = KeyStore.getInstance("CAPI"); //$NON-NLS-1$
		}
        if (keyStore != null) {
            keyStore.load(null, null);
            //for (Enumeration<String> aliasEnumeration = keyStore.aliases();aliasEnumeration.hasMoreElements();) {
            for (Enumeration aliasEnumeration = keyStore.aliases();aliasEnumeration.hasMoreElements();) {
            	String alias = (String) aliasEnumeration.nextElement();
            	String issuer = ""; //$NON-NLS-1$
            	Certificate cert = keyStore.getCertificate(alias);
            	if (cert instanceof X509Certificate) {
            		issuer = ((X509Certificate) cert).getIssuerDN().getName();
            	}
            	list.add(new String[]{alias,issuer});
            	//keyStore.getCertificate(alias)
            }
        }
	} catch (Exception e) {
		SVNUIPlugin.log(IStatus.ERROR, e.getMessage(), e);
	}
       setTitle(Policy.bind("SSLClientCertificatesMSCapi.0"));
       setAddCancelButton(true);
       LabelProvider lp = new LabelProvider(){
       	public String getText(Object element) {
       		if (element == null) {
       			return ""; //$NON-NLS-1$
       		} else if (element instanceof String[] && ((String[]) element).length > 1) {
       			return ((String[]) element)[0] + " | issued by: " + ((String[]) element)[1]; //$NON-NLS-1$
       		} else {
       			return element.toString();
       		}
       	}
       };
       setLabelProvider(lp);
       setMessage(Policy.bind("SSLClientCertificatesMSCapi.1"));
       setContentProvider(new ListContentProvider());
       setInput(list);
}