java.security.KeyStore#aliases ( )源码实例Demo

下面列出了java.security.KeyStore#aliases ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: openjdk-jdk9   文件: Main.java
/**
 * 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;
}
 
源代码2 项目: AndroidHttpCapture   文件: TrustUtil.java
/**
 * 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);
    }
}
 
源代码3 项目: Bytecoder   文件: Main.java
/**
 * 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;
}
 
源代码4 项目: davmail   文件: ClientCertificateTest.java
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());
    }
}
 
源代码5 项目: android-testdpc   文件: CertificateUtil.java
/**
 * 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;
}
 
源代码6 项目: carbon-identity   文件: KeyStoreAdminClient.java
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;
    }
}
 
源代码7 项目: jdk-1.7-annotated   文件: PKIXParameters.java
/**
 * 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>();
}
 
源代码8 项目: jdk8u60   文件: PKIXParameters.java
/**
 * 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>();
}
 
源代码9 项目: itext2   文件: PdfPKCS7.java
/**
 * 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;
}
 
源代码10 项目: eet-client   文件: ClientKey.java
private Enumeration<String> getAliases(final KeyStore keystore) throws InvalidKeystoreException {
    try {
        return keystore.aliases();
    } catch (final KeyStoreException e) {
        throw new InvalidKeystoreException(e);
    }
}
 
源代码11 项目: jdk8u60   文件: KeyStoreResolver.java
/**
 * 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);
    }
}
 
源代码12 项目: Aria   文件: KeyManagerUtils.java
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");
}
 
源代码13 项目: openjdk-jdk9   文件: IterateWindowsRootStore.java
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.");
    }
}
 
源代码14 项目: jdk8u-dev-jdk   文件: KeyStoreResolver.java
/**
 * 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);
    }
}
 
源代码15 项目: athenz   文件: KeyStoreTest.java
@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);
}
 
@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);
  }

}
 
源代码17 项目: MaxKey   文件: ConsumerEndpoint.java
/**
 * 初始化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);
	}
}
 
/**
    *
 * @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);
}
 
源代码19 项目: jdk8u-jdk   文件: ReadP12Test.java
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");
        }

    }
 
源代码20 项目: SPDS   文件: KeystoreLongTest.java
@Test
public void test2() throws KeyStoreException {
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.aliases();
    mustBeInErrorState(ks);
}