List of usage examples for java.security KeyStore aliases
public final Enumeration<String> aliases() throws KeyStoreException
From source file:net.sf.keystore_explorer.crypto.x509.X509CertUtil.java
private static List<X509Certificate> extractCertificates(KeyStore keyStore) throws CryptoException { try {// w w w . j av a 2 s .c om List<X509Certificate> certs = new ArrayList<X509Certificate>(); for (Enumeration aliases = keyStore.aliases(); aliases.hasMoreElements();) { String alias = (String) aliases.nextElement(); if (keyStore.isCertificateEntry(alias)) { certs.add(X509CertUtil.convertCertificate(keyStore.getCertificate(alias))); } } return certs; } catch (KeyStoreException ex) { throw new CryptoException(res.getString("NoExtractCertificates.exception.message"), ex); } }
From source file:net.sf.jsignpdf.utils.KeyStoreUtils.java
/** * Returns list of key aliases in given keystore. * //www . jav a2s . c o m * @param aKs * @param options * @return */ private static List<String> getAliasesList(final KeyStore aKs, final BasicSignerOptions options) { if (options == null) { throw new NullPointerException("Options are empty."); } if (aKs == null) { throw new NullPointerException(RES.get("error.keystoreNull")); } final List<String> tmpResult = new ArrayList<String>(); try { LOGGER.info(RES.get("console.getAliases")); final Enumeration<String> tmpAliases = aKs.aliases(); final boolean checkValidity = ConfigProvider.getInstance().getAsBool("certificate.checkValidity", true); final boolean checkKeyUsage = ConfigProvider.getInstance().getAsBool("certificate.checkKeyUsage", true); final boolean checkCriticalExtensions = ConfigProvider.getInstance() .getAsBool("certificate.checkCriticalExtensions", true); while (tmpAliases.hasMoreElements()) { String tmpAlias = tmpAliases.nextElement(); if (aKs.isKeyEntry(tmpAlias)) { final Certificate tmpCert = aKs.getCertificate(tmpAlias); boolean tmpAddAlias = true; if (tmpCert instanceof X509Certificate) { final X509Certificate tmpX509 = (X509Certificate) tmpCert; if (checkValidity) { try { tmpX509.checkValidity(); } catch (CertificateExpiredException e) { LOGGER.info(RES.get("console.certificateExpired", tmpAlias)); tmpAddAlias = false; } catch (CertificateNotYetValidException e) { LOGGER.info(RES.get("console.certificateNotYetValid", tmpAlias)); tmpAddAlias = false; } } if (checkKeyUsage) { // check if the certificate is supposed to be // used for digital signatures final boolean keyUsage[] = tmpX509.getKeyUsage(); if (keyUsage != null && keyUsage.length > 0) { // KeyUsage ::= BIT STRING { // digitalSignature (0), // nonRepudiation (1), // keyEncipherment (2), // dataEncipherment (3), // keyAgreement (4), // keyCertSign (5), // cRLSign (6), // encipherOnly (7), // decipherOnly (8) } if (!(keyUsage[0] || keyUsage[1])) { LOGGER.info(RES.get("console.certificateNotForSignature", tmpAlias)); tmpAddAlias = false; } } } // check critical extensions if (checkCriticalExtensions) { final Set<String> criticalExtensionOIDs = tmpX509.getCriticalExtensionOIDs(); if (criticalExtensionOIDs != null) { for (String oid : criticalExtensionOIDs) { if (!Constants.SUPPORTED_CRITICAL_EXTENSION_OIDS.contains(oid)) { LOGGER.info( RES.get("console.criticalExtensionNotSupported", tmpAlias, oid)); tmpAddAlias = false; } } } } } if (tmpAddAlias) { tmpResult.add(tmpAlias); } } } } catch (Exception e) { LOGGER.error(RES.get("console.exception"), e); } return tmpResult; }
From source file:org.signserver.server.cryptotokens.CryptoTokenHelper.java
/** * Performs test signatures for the specified keys or for all if "all" specified. * @param keyStore Loaded keystore to read keys from * @param alias Alias of key to test or "all" to test all * @param authCode Key password (if used, ie for JKS only) * @param signatureProvider Provider for creating the signature * @return The results for each key found * @throws CryptoTokenOfflineException In case the key could not be used *//* w w w.j av a 2 s .c o m*/ public static Collection<KeyTestResult> testKey(KeyStore keyStore, String alias, char[] authCode, String signatureProvider) throws CryptoTokenOfflineException { if (LOG.isDebugEnabled()) { LOG.debug("testKey for alias: " + alias); } final Collection<KeyTestResult> result = new LinkedList<KeyTestResult>(); try { final Enumeration<String> e = keyStore.aliases(); while (e.hasMoreElements()) { final String keyAlias = e.nextElement(); if (alias.equalsIgnoreCase(ICryptoToken.ALL_KEYS) || alias.equals(keyAlias)) { if (LOG.isDebugEnabled()) { LOG.debug("checking keyAlias: " + keyAlias); } if (keyStore.isKeyEntry(keyAlias)) { String status; String publicKeyHash = null; boolean success = false; try { final PrivateKey privateKey = (PrivateKey) keyStore.getKey(keyAlias, authCode); final Certificate entryCert = keyStore.getCertificate(keyAlias); if (entryCert != null) { final PublicKey publicKey = entryCert.getPublicKey(); publicKeyHash = createKeyHash(publicKey); testSignAndVerify(privateKey, publicKey, signatureProvider); success = true; status = ""; } else { status = "Not testing keys with alias " + keyAlias + ". No certificate exists."; } } catch (ClassCastException ce) { status = "Not testing keys with alias " + keyAlias + ". Not a private key."; } catch (InvalidKeyException ex) { LOG.error("Error testing key: " + keyAlias, ex); status = ex.getMessage(); } catch (KeyStoreException ex) { LOG.error("Error testing key: " + keyAlias, ex); status = ex.getMessage(); } catch (NoSuchAlgorithmException ex) { LOG.error("Error testing key: " + keyAlias, ex); status = ex.getMessage(); } catch (NoSuchProviderException ex) { LOG.error("Error testing key: " + keyAlias, ex); status = ex.getMessage(); } catch (SignatureException ex) { LOG.error("Error testing key: " + keyAlias, ex); status = ex.getMessage(); } catch (UnrecoverableKeyException ex) { LOG.error("Error testing key: " + keyAlias, ex); status = ex.getMessage(); } result.add(new KeyTestResult(keyAlias, success, status, publicKeyHash)); } } } } catch (KeyStoreException ex) { throw new CryptoTokenOfflineException(ex); } if (LOG.isDebugEnabled()) { LOG.debug("<testKey"); } return result; }
From source file:org.signserver.server.cryptotokens.CryptoTokenHelper.java
public static TokenSearchResults searchTokenEntries(final KeyStore keyStore, final int startIndex, final int max, final QueryCriteria qc, final boolean includeData) throws CryptoTokenOfflineException, QueryException { final TokenSearchResults result; try {/*from w ww. j a v a 2 s.c o m*/ final ArrayList<TokenEntry> tokenEntries = new ArrayList<TokenEntry>(); final Enumeration<String> e = keyStore.aliases(); // We assume the order is the same for every call unless entries has been added or removed final long maxIndex = (long) startIndex + max; for (int i = 0; i < maxIndex && e.hasMoreElements();) { final String keyAlias = e.nextElement(); final String type; if (keyStore.entryInstanceOf(keyAlias, KeyStore.PrivateKeyEntry.class)) { type = TokenEntry.TYPE_PRIVATEKEY_ENTRY; } else if (keyStore.entryInstanceOf(keyAlias, KeyStore.SecretKeyEntry.class)) { type = TokenEntry.TYPE_SECRETKEY_ENTRY; } else if (keyStore.entryInstanceOf(keyAlias, KeyStore.TrustedCertificateEntry.class)) { type = TokenEntry.TYPE_TRUSTED_ENTRY; } else { type = null; } TokenEntry entry = new TokenEntry(keyAlias, type); if (shouldBeIncluded(entry, qc)) { if (i < startIndex) { i++; continue; } if (LOG.isDebugEnabled()) { LOG.debug("checking keyAlias: " + keyAlias); } // Add additional data if (includeData) { Map<String, String> info = new HashMap<String, String>(); try { Date creationDate = keyStore.getCreationDate(keyAlias); entry.setCreationDate(creationDate); } catch (ProviderException ex) { } // NOPMD: We ignore if it is not supported if (TokenEntry.TYPE_PRIVATEKEY_ENTRY.equals(type)) { final Certificate[] chain = keyStore.getCertificateChain(keyAlias); if (chain.length > 0) { info.put(INFO_KEY_ALGORITHM, AlgorithmTools.getKeyAlgorithm(chain[0].getPublicKey())); info.put(INFO_KEY_SPECIFICATION, AlgorithmTools.getKeySpecification(chain[0].getPublicKey())); } try { entry.setParsedChain(chain); } catch (CertificateEncodingException ex) { info.put("Error", ex.getMessage()); LOG.error("Certificate could not be encoded for alias: " + keyAlias, ex); } } else if (TokenEntry.TYPE_TRUSTED_ENTRY.equals(type)) { Certificate certificate = keyStore.getCertificate(keyAlias); try { entry.setParsedTrustedCertificate(certificate); } catch (CertificateEncodingException ex) { info.put("Error", ex.getMessage()); LOG.error("Certificate could not be encoded for alias: " + keyAlias, ex); } } else if (TokenEntry.TYPE_SECRETKEY_ENTRY.equals(type)) { try { KeyStore.Entry entry1 = keyStore.getEntry(keyAlias, null); SecretKey secretKey = ((KeyStore.SecretKeyEntry) entry1).getSecretKey(); info.put(INFO_KEY_ALGORITHM, secretKey.getAlgorithm()); //info.put(INFO_KEY_SPECIFICATION, AlgorithmTools.getKeySpecification(chain[0].getPublicKey())); // TODO: Key specification support for secret keys } catch (NoSuchAlgorithmException ex) { info.put("Error", ex.getMessage()); LOG.error("Unable to get secret key for alias: " + keyAlias, ex); } catch (UnrecoverableEntryException ex) { info.put("Error", ex.getMessage()); LOG.error("Unable to get secret key for alias: " + keyAlias, ex); } } entry.setInfo(info); } tokenEntries.add(entry); // Increase index i++; } } result = new TokenSearchResults(tokenEntries, e.hasMoreElements()); } catch (KeyStoreException ex) { throw new CryptoTokenOfflineException(ex); } return result; }
From source file:com.thoughtworks.go.security.AuthSSLX509TrustManagerFactory.java
private void logKeyStore(KeyStore store) throws KeyStoreException { Enumeration aliases = store.aliases(); while (aliases.hasMoreElements()) { String alias = (String) aliases.nextElement(); LOG.debug("Trusted certificate '" + alias + "':"); Certificate trustedcert = store.getCertificate(alias); if (trustedcert != null && trustedcert instanceof X509Certificate) { X509Certificate cert = (X509Certificate) trustedcert; 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()); }// w ww .ja va 2s . co m } }
From source file:test.be.fedict.eid.applet.MSCAPITest.java
@Test public void testMSCAPI() throws Exception { KeyStore keyStore = KeyStore.getInstance("Windows-MY"); keyStore.load(null, null);/*from www .j ava 2s . co m*/ Enumeration<String> aliases = keyStore.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); LOG.debug("alias: " + alias); X509Certificate certificate = (X509Certificate) keyStore.getCertificate(alias); LOG.debug("certificate subject: " + certificate.getSubjectX500Principal()); } }
From source file:nu.yona.server.AppServiceApplication.java
private void logAliases(KeyStore keyStore) { try {//from ww w .j a v a 2s.c o m Enumeration<String> aliasEnum = keyStore.aliases(); while (aliasEnum.hasMoreElements()) { logger.info("Key store contains alias '{}'", aliasEnum.nextElement()); } } catch (KeyStoreException e) { throw YonaException.unexpected(e); } }
From source file:com.thoughtworks.go.security.AuthSSLKeyManagerFactory.java
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()); }/*from ww w . j ava 2s . c om*/ } } } }
From source file:test.integ.be.agiv.security.PKCS12Test.java
@Test public void testLoadPKCS12() throws Exception { Config config = new Config(); String pkcs12Path = config.getPKCS12Path(); String pkcs12Password = config.getPKCS12Password(); InputStream pkcs12InputStream = new FileInputStream(pkcs12Path); assertNotNull(pkcs12InputStream); LOG.debug("loading PKCS12 keystore"); KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load(pkcs12InputStream, pkcs12Password.toCharArray()); Enumeration<String> aliases = keyStore.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); LOG.debug("alias: " + alias); X509Certificate certificate = (X509Certificate) keyStore.getCertificate(alias); LOG.debug("certificate: " + certificate); PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, pkcs12Password.toCharArray()); LOG.debug("private key algo: " + privateKey.getAlgorithm()); assertEquals("RSA", privateKey.getAlgorithm()); LOG.debug("certificate fingerprint: " + DigestUtils.shaHex(certificate.getEncoded())); }// w w w .j a v a2s .c om }
From source file:com.netscape.cmstools.pkcs11.PKCS11CertFindCLI.java
public void execute(String[] args) throws Exception { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("help")) { printHelp();//from w ww . j a va 2s . c om return; } if (cmd.hasOption("verbose")) { PKILogger.setLevel(PKILogger.Level.INFO); } else if (cmd.hasOption("debug")) { PKILogger.setLevel(PKILogger.Level.DEBUG); } String tokenName = getConfig().getTokenName(); CryptoToken token = CryptoUtil.getKeyStorageToken(tokenName); KeyStore ks = KeyStore.getInstance("pkcs11"); ks.load(new JSSLoadStoreParameter(token)); Enumeration<String> aliases = ks.aliases(); boolean first = true; while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); Certificate cert = ks.getCertificate(alias); if (cert == null) { continue; } if (first) { first = false; } else { System.out.println(); } PKCS11CertCLI.printCertInfo(alias, cert); } }