List of usage examples for java.security KeyStore isKeyEntry
public final boolean isKeyEntry(String alias) throws KeyStoreException
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 *//*from w w w. j av a 2 s .c om*/ 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:ch.cyberduck.core.ssl.CertificateStoreX509KeyManager.java
@Override public PrivateKey getPrivateKey(final String alias) { try {//from w w w . j a v a 2s . c o m final KeyStore store; try { store = this.getKeystore(); } catch (IOException e) { return null; } if (store.isKeyEntry(alias)) { final Key key = store.getKey(alias, "null".toCharArray()); if (key instanceof PrivateKey) { return (PrivateKey) key; } else { log.warn(String.format("Key %s for alias %s is not a private key", key, alias)); } } else { log.warn(String.format("Alias %s is not a key entry", alias)); } } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException e) { log.error(String.format("Keystore not loaded %s", e.getMessage())); } log.warn(String.format("No private key for alias %s", alias)); // Return null if the alias can't be found return null; }
From source file:org.wso2.carbon.security.ui.client.KeyStoreAdminClient.java
public boolean isPrivateKeyStore(byte[] content, String password, String type) throws java.lang.Exception { try {/*from www .ja v a 2 s . com*/ 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; } }
From source file:org.lockss.util.TestKeyStoreUtil.java
void assertPrivateKs(File file, String pass, String alias) throws Exception { KeyStore ks = loadKeyStore("jceks", file, alias); List aliases = ListUtil.fromIterator(new EnumerationIterator(ks.aliases())); assertEquals(2, aliases.size());//from ww w . ja va2 s. c o m Certificate cert = ks.getCertificate(alias + ".crt"); assertNotNull(cert); assertEquals("X.509", cert.getType()); assertTrue(ks.isKeyEntry(alias + ".key")); assertTrue(ks.isCertificateEntry(alias + ".crt")); Key key = ks.getKey(alias + ".key", pass.toCharArray()); assertNotNull(key); assertEquals("RSA", key.getAlgorithm()); }
From source file:org.eclipse.gyrex.http.jetty.internal.admin.CertificateDefinition.java
@Override public String getInfo() { try {/*from ww w .j ava2 s . co m*/ final StrBuilder certInfo = new StrBuilder(); final KeyStore ks = getKeyStore(); final Enumeration aliases = ks.aliases(); while (aliases.hasMoreElements()) { final String alias = (String) aliases.nextElement(); if (!certInfo.isEmpty()) { certInfo.append(", "); } // certInfo.append(alias).append(": "); if (ks.isKeyEntry(alias)) { Certificate[] chain = ks.getCertificateChain(alias); if (null == chain) { final Certificate certificate = ks.getCertificate(alias); chain = new Certificate[] { certificate }; } for (int i = 0; i < chain.length; i++) { if (i > 0) { certInfo.append(" "); } final Certificate certificate = chain[i]; if (certificate instanceof X509Certificate) { final X509Certificate x509 = (X509Certificate) certificate; final X500PrincipalHelper helper = new X500PrincipalHelper( x509.getSubjectX500Principal()); certInfo.append(helper.getCN()); certInfo.append(", valid till ").append(TO_STRING_FORMAT.format(x509.getNotAfter())); } else { certInfo.append("INVALID"); } } } else { certInfo.append("IGNORED"); } } return StringUtils.trim(certInfo.toString()); } catch (final Exception e) { return ExceptionUtils.getRootCauseMessage(e); } }
From source file:net.sf.jsignpdf.utils.KeyStoreUtils.java
/** * Returns list of key aliases in given keystore. * //from w ww. j a v a 2s . 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:mitm.common.tools.PfxTool.java
private void mergePfx() throws Exception { if (StringUtils.isEmpty(destFile)) { throw new MissingOptionException(destOption.getOpt() + " is missing."); }//from ww w. ja v a 2 s . c om if (StringUtils.isEmpty(destPassword)) { throw new MissingOptionException(destPasswordOption.getOpt() + " is missing."); } KeyStore inStore = loadKeyStore(inFile, true, inPassword); KeyStore destStore = loadKeyStore(destFile, false, destPassword); Enumeration<String> aliases = inStore.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); String destAlias = retainAliases ? alias : UUID.randomUUID().toString() + "_" + alias; if (inStore.isKeyEntry(alias)) { KeyStore.Entry entry = inStore.getEntry(alias, new KeyStore.PasswordProtection(inPassword.toCharArray())); destStore.setEntry(destAlias, entry, new KeyStore.PasswordProtection(destPassword.toCharArray())); } else { Certificate certificate = inStore.getCertificate(alias); destStore.setCertificateEntry(destAlias, certificate); } } destStore.store(new FileOutputStream(destFile), destPassword.toCharArray()); }
From source file:net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImplTest.java
/** * @throws java.lang.Exception/*from ww w. j a v a2s . c o m*/ */ @BeforeClass public static void setUpBeforeClass() throws Exception { // Just in case, add the BouncyCastle provider // It gets added from the CredentialManagerImpl constructor as well // but we may need some crypto operations before we invoke the Cred. Manager Security.addProvider(new BouncyCastleProvider()); // Create a test username and password for a service serviceURI = new URI("http://someservice"); usernamePassword = new UsernamePassword("testuser", "testpasswd"); // Load the test private key and its certificate File privateKeyCertFile = new File(privateKeyFileURL.getPath()); KeyStore pkcs12Keystore = java.security.KeyStore.getInstance("PKCS12", "BC"); // We have to use the BC provider here as the certificate chain is not loaded if we use whichever provider is first in Java!!! FileInputStream inStream = new FileInputStream(privateKeyCertFile); pkcs12Keystore.load(inStream, privateKeyAndPKCS12KeystorePassword.toCharArray()); // KeyStore pkcs12Keystore = credentialManager.loadPKCS12Keystore(privateKeyCertFile, privateKeyPassword); Enumeration<String> aliases = pkcs12Keystore.aliases(); while (aliases.hasMoreElements()) { // The test-private-key-cert.p12 file contains only one private key // and corresponding certificate entry String alias = aliases.nextElement(); if (pkcs12Keystore.isKeyEntry(alias)) { // is it a (private) key entry? privateKey = pkcs12Keystore.getKey(alias, privateKeyAndPKCS12KeystorePassword.toCharArray()); privateKeyCertChain = pkcs12Keystore.getCertificateChain(alias); break; } } inStream.close(); // Load the test trusted certificate (belonging to *.Google.com) File trustedCertFile = new File(trustedCertficateFileURL.getPath()); inStream = new FileInputStream(trustedCertFile); CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); trustedCertficate = (X509Certificate) certFactory.generateCertificate(inStream); try { inStream.close(); } catch (Exception e) { // Ignore } keystoreChangedObserver = new Observer<KeystoreChangedEvent>() { @Override public void notify(Observable<KeystoreChangedEvent> sender, KeystoreChangedEvent message) throws Exception { // TODO Auto-generated method stub } }; }
From source file:org.dasein.cloud.google.GoogleMethod.java
static @Nonnull String getToken(@Nonnull String iss, @Nonnull String p12File) throws CloudException { if (logger.isDebugEnabled()) { logger.debug("iss: " + iss); logger.debug("p12File: " + p12File); }//from w w w. ja v a2 s . com String header = "{\"alg\":\"RS256\",\"typ\":\"JWT\"}"; StringBuffer token = new StringBuffer(); try { token.append(Base64.encodeBase64URLSafeString(header.getBytes("UTF-8"))); token.append("."); String scope = "https://www.googleapis.com/auth/compute"; String aud = "https://accounts.google.com/o/oauth2/token"; String expiry = Long.toString((System.currentTimeMillis() / 1000) + 3600); String startTime = Long.toString((System.currentTimeMillis() / 1000)); String payload = "{\"iss\": \"" + iss + "\", \"scope\": \"" + scope + "\", \"aud\": \"" + aud + "\", \"exp\": \"" + expiry + "\", \"iat\": \"" + startTime + "\"}"; token.append(Base64.encodeBase64URLSafeString(payload.getBytes("UTF-8"))); // TODO: the password is hardcoded. This has to be read from the ctx or from the environment variable char[] password = "notasecret".toCharArray(); FileInputStream iStream = new FileInputStream(new File(p12File)); KeyStore store = KeyStore.getInstance("PKCS12"); try { store.load(iStream, password); } finally { try { iStream.close(); } catch (IOException e) { e.printStackTrace(); logger.error("Could not read the keystore file"); throw new CloudException(e); } } String alias = ""; Enumeration<String> aliases = store.aliases(); while (aliases.hasMoreElements()) { String keyStoreAlias = aliases.nextElement().toString(); if (store.isKeyEntry(keyStoreAlias)) { alias = keyStoreAlias; break; } } PrivateKey privateKey = (PrivateKey) store.getKey(alias, password); Signature shaSignature = Signature.getInstance("SHA256withRSA"); shaSignature.initSign(privateKey); shaSignature.update(token.toString().getBytes("UTF-8")); String signedToken = Base64.encodeBase64URLSafeString(shaSignature.sign()); //Separate with a period token.append("."); //Add the encoded signature token.append(signedToken); return token.toString(); } catch (Exception e) { e.printStackTrace(); logger.error("Could not sign the payload with the private key"); throw new CloudException(e); } }
From source file:org.apache.taverna.security.credentialmanager.impl.CredentialManagerImplTest.java
/** * @throws java.lang.Exception/*from w w w . ja v a2s . c om*/ */ @BeforeClass public static void setUpBeforeClass() throws Exception { // Just in case, add the BouncyCastle provider // It gets added from the CredentialManagerImpl constructor as well // but we may need some crypto operations before we invoke the Cred. Manager Security.addProvider(new BouncyCastleProvider()); // Create a test username and password for a service serviceURI = new URI("http://someservice"); usernamePassword = new UsernamePassword("testuser", "testpasswd"); // Load the test private key and its certificate File privateKeyCertFile = new File(privateKeyFileURL.getPath()); KeyStore pkcs12Keystore = java.security.KeyStore.getInstance("PKCS12", "BC"); // We have to use the BC provider here as the certificate chain is not loaded if we use whichever provider is first in Java!!! FileInputStream inStream = new FileInputStream(privateKeyCertFile); pkcs12Keystore.load(inStream, privateKeyAndPKCS12KeystorePassword.toCharArray()); // KeyStore pkcs12Keystore = credentialManager.loadPKCS12Keystore(privateKeyCertFile, privateKeyPassword); Enumeration<String> aliases = pkcs12Keystore.aliases(); while (aliases.hasMoreElements()) { // The test-private-key-cert.p12 file contains only one private key // and corresponding certificate entry String alias = aliases.nextElement(); if (pkcs12Keystore.isKeyEntry(alias)) { // is it a (private) key entry? privateKey = pkcs12Keystore.getKey(alias, privateKeyAndPKCS12KeystorePassword.toCharArray()); privateKeyCertChain = pkcs12Keystore.getCertificateChain(alias); break; } } inStream.close(); // Load the test trusted certificate (belonging to *.Google.com) File trustedCertFile = new File(trustedCertficateFileURL.getPath()); inStream = new FileInputStream(trustedCertFile); CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); trustedCertficate = (X509Certificate) certFactory.generateCertificate(inStream); try { inStream.close(); } catch (Exception e) { // Ignore } keystoreChangedObserver = new Observer<KeystoreChangedEvent>() { @Override public void notify(Observable<KeystoreChangedEvent> sender, KeystoreChangedEvent message) throws Exception { // TODO Auto-generated method stub } }; }