List of usage examples for java.security KeyStore aliases
public final Enumeration<String> aliases() throws KeyStoreException
From source file:eu.eidas.auth.engine.EIDASSAMLEngine.java
/** * Gets the alias from X.509 Certificate at keystore. * //from www.j ava 2 s.c o m * @param keyInfo the key info * @param ownKeyStore * @param ownKeyStore * * @return the alias */ private String getAlias(final KeyInfo keyInfo, KeyStore ownKeyStore) { LOG.trace("Recover alias information"); String alias = null; try { final org.opensaml.xml.signature.X509Certificate xmlCert = keyInfo.getX509Datas().get(0) .getX509Certificates().get(0); // Transform the KeyInfo to X509Certificate. CertificateFactory certFact; certFact = CertificateFactory.getInstance("X.509"); final ByteArrayInputStream bis = new ByteArrayInputStream(Base64.decode(xmlCert.getValue())); final X509Certificate cert = (X509Certificate) certFact.generateCertificate(bis); final String tokenSerialNumber = cert.getSerialNumber().toString(HEXA); final X500Name tokenIssuerDN = new X500Name(cert.getIssuerDN().getName()); String aliasCert; X509Certificate certificate; boolean find = false; for (final Enumeration<String> e = ownKeyStore.aliases(); e.hasMoreElements() && !find;) { aliasCert = e.nextElement(); certificate = (X509Certificate) ownKeyStore.getCertificate(aliasCert); final String serialNum = certificate.getSerialNumber().toString(HEXA); X500Name issuerDN = new X500Name(certificate.getIssuerDN().getName()); if (serialNum.equalsIgnoreCase(tokenSerialNumber) && X500PrincipalUtil.principalEquals(issuerDN, tokenIssuerDN)) { alias = aliasCert; find = true; } } } catch (KeyStoreException e) { LOG.info(SAML_EXCHANGE, "BUSINESS EXCEPTION : Procces getAlias from certificate associated into the signing keystore: {}", e.getMessage()); LOG.debug(SAML_EXCHANGE, "BUSINESS EXCEPTION : Procces getAlias from certificate associated into the signing keystore: {}", e); } catch (CertificateException e) { LOG.info(SAML_EXCHANGE, "BUSINESS EXCEPTION : Procces getAlias from certificate associated into the signing keystore: {}", e.getMessage()); LOG.debug(SAML_EXCHANGE, "BUSINESS EXCEPTION : Procces getAlias from certificate associated into the signing keystore: {}", e); } catch (RuntimeException e) { LOG.info(SAML_EXCHANGE, "BUSINESS EXCEPTION : Procces getAlias from certificate associated into the signing keystore: {}", e.getMessage()); LOG.debug(SAML_EXCHANGE, "BUSINESS EXCEPTION : Procces getAlias from certificate associated into the signing keystore: {}", e); } return alias; }
From source file:org.renci.ahab.ndllib.transport.OrcaSMXMLRPCProxy.java
/** * Set the identity for the communications to the XMLRPC controller. Eventually * we may talk to several controller with different identities. For now only * one is configured.// w w w. jav a 2 s . c o m */ private void setSSLIdentity() throws Exception { //if (sslIdentitySet) // return; //System.out.println("In setSSLIdentity()"); try { // create multikeymanager mkm = new MultiKeyManager(); //TODO //URL ctrlrUrl = new URL(GUI.getInstance().getSelectedController()); URL ctrlrUrl = new URL(CONTROLLER_URL); // TODO // register a new protocol ContextualSSLProtocolSocketFactory regSslFact = new ContextualSSLProtocolSocketFactory(); // add this multikey context factory for the controller host/port regSslFact.addHostContextFactory(new MultiKeySSLContextFactory(mkm, trustAllCerts), ctrlrUrl.getHost(), ctrlrUrl.getPort()); if (rmProperties == null) { System.out.println("ERROR ... Property File with user credentials not supplied..."); return; } KeyStore ks = null; //File keyStorePath = loadUserFile("/Users/anirban/Misc/tmp/renci-openvpn/flukes.jks"); //File certFilePath = loadUserFile("/Users/anirban/.ssl/geni-anirban.pem"); //File certKeyFilePath = loadUserFile("/Users/anirban/.ssl/geni-anirban.pem"); File keyStorePath = null; File certFilePath = null; File certKeyFilePath = null; if (rmProperties.getProperty(USER_KEYSTORE_PATH_PROP) != null) { keyStorePath = loadUserFile(rmProperties.getProperty(USER_KEYSTORE_PATH_PROP)); } if (rmProperties.getProperty(USER_CERTFILE_PATH_PROP) != null) { certFilePath = loadUserFile(rmProperties.getProperty(USER_CERTFILE_PATH_PROP)); } if (rmProperties.getProperty(USER_CERTKEYFILE_PATH_PROP) != null) { certKeyFilePath = loadUserFile(rmProperties.getProperty(USER_CERTKEYFILE_PATH_PROP)); } String keyAlias = null, keyPassword = null; if (keyStorePath != null && keyStorePath.exists()) { // load keystore and get the right cert from it System.out.println("Reading auth details from keystore"); //TODO keyAlias = rmProperties.getProperty(USER_KEYSTORE_KEYALIAS_PROP); keyPassword = rmProperties.getProperty(USER_KEYSTORE_KEYPASS_PROP); //TODO FileInputStream jksIS = new FileInputStream(keyStorePath); ks = loadJKSData(jksIS, keyAlias, keyPassword); jksIS.close(); } else if (certFilePath != null && certKeyFilePath != null && certFilePath.exists() && certKeyFilePath.exists()) { System.out.println("Reading auth details from cert file and certkeyfile"); FileInputStream certIS = new FileInputStream(certFilePath); FileInputStream keyIS = new FileInputStream(certKeyFilePath); keyAlias = "x509convert"; //TODO keyPassword = rmProperties.getProperty(USER_KEYPASS_PROP); //TODO ks = loadX509Data(certIS, keyIS, keyAlias, keyPassword); certIS.close(); keyIS.close(); } if (ks == null) throw new Exception("Was unable to find either: " + keyStorePath.getCanonicalPath() + " or the pair of: " + certFilePath.getCanonicalPath() + " and " + certKeyFilePath.getCanonicalPath() + " as specified."); // check that the spelling of key alias is proper Enumeration<String> as = ks.aliases(); while (as.hasMoreElements()) { String a = as.nextElement(); if (keyAlias.toLowerCase().equals(a.toLowerCase())) { keyAlias = a; break; } } // alias has to exist and have a key and cert present if (!ks.containsAlias(keyAlias)) { throw new Exception("Alias " + keyAlias + " does not exist in keystore " + keyStorePath + "."); } if (ks.getKey(keyAlias, keyPassword.toCharArray()) == null) throw new Exception( "Key with alias " + keyAlias + " does not exist in keystore " + keyStorePath + "."); if (ks.getCertificate(keyAlias) == null) { throw new Exception( "Certificate with alias " + keyAlias + " does not exist in keystore " + keyStorePath + "."); } if (ks.getCertificate(keyAlias).getType().equals("X.509")) { X509Certificate x509Cert = (X509Certificate) ks.getCertificate(keyAlias); try { x509Cert.checkValidity(); } catch (Exception e) { throw new Exception("Certificate with alias " + keyAlias + " is not yet valid or has expired."); } } // add the identity into it mkm.addPrivateKey(keyAlias, (PrivateKey) ks.getKey(keyAlias, keyPassword.toCharArray()), ks.getCertificate(keyAlias)); // before we do SSL to this controller, set our identity mkm.setCurrentGuid(keyAlias); // register the protocol (Note: All xmlrpc clients must use XmlRpcCommonsTransportFactory // for this to work). See ContextualSSLProtocolSocketFactory. Protocol reghhttps = new Protocol("https", (ProtocolSocketFactory) regSslFact, 443); Protocol.registerProtocol("https", reghhttps); sslIdentitySet = true; } catch (Exception e) { e.printStackTrace(); throw new Exception("Unable to load user private key and certificate from the keystore: " + e); } //System.out.println("Exiting setSSLIdentity"); }
From source file:eu.stork.peps.auth.engine.STORKSAMLEngine.java
/** * Gets the alias from X.509 Certificate at keystore. * /*from w w w . j ava 2 s . com*/ * @param keyInfo the key info * @param storkOwnKeyStore * @param storkOwnKeyStore * * @return the alias */ private String getAlias(final KeyInfo keyInfo, KeyStore storkOwnKeyStore) { LOG.debug("Recover alias information"); String alias = null; try { final org.opensaml.xml.signature.X509Certificate xmlCert = keyInfo.getX509Datas().get(0) .getX509Certificates().get(0); // Transform the KeyInfo to X509Certificate. CertificateFactory certFact; certFact = CertificateFactory.getInstance("X.509"); final ByteArrayInputStream bis = new ByteArrayInputStream(Base64.decode(xmlCert.getValue())); final X509Certificate cert = (X509Certificate) certFact.generateCertificate(bis); final String tokenSerialNumber = cert.getSerialNumber().toString(16); final X509Principal tokenIssuerDN = new X509Principal(cert.getIssuerDN().getName()); String aliasCert; X509Certificate certificate; boolean find = false; for (final Enumeration<String> e = storkOwnKeyStore.aliases(); e.hasMoreElements() && !find;) { aliasCert = e.nextElement(); certificate = (X509Certificate) storkOwnKeyStore.getCertificate(aliasCert); final String serialNum = certificate.getSerialNumber().toString(16); X509Principal issuerDN = new X509Principal(certificate.getIssuerDN().getName()); if (serialNum.equalsIgnoreCase(tokenSerialNumber) && X509PrincipalUtil.equals2(issuerDN, tokenIssuerDN)) { alias = aliasCert; find = true; } } } catch (KeyStoreException e) { LOG.error("Procces getAlias from certificate associated into the signing keystore..", e); } catch (CertificateException e) { LOG.error("Procces getAlias from certificate associated into the signing keystore..", e); } catch (RuntimeException e) { LOG.error("Procces getAlias from certificate associated into the signing keystore..", e); } return alias; }
From source file:net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImpl.java
/** * Load Taverna's Truststore from a file on a disk. If the Truststore does * not already exist, a new empty one will be created and contents of Java's * truststore located in <JAVA_HOME>/lib/security/cacerts will be copied * over to the Truststore./*from ww w . ja va 2 s . co m*/ */ private void loadTruststore() throws CMException { if (truststore != null) return; try { /* * Try to create Taverna's Truststore as Bouncy Castle UBER-type * keystore. */ truststore = KeyStore.getInstance("UBER", "BC"); } catch (Exception ex) { /* * The requested keystore type is not available from security * providers. */ throw new CMException("Failed to instantiate Taverna's Truststore", ex); } if (truststoreFile.exists()) { /* * If the Truststore file already exists, open it and load the * Truststore */ try (FileInputStream fis = new FileInputStream(truststoreFile)) { // Load the Truststore from the file truststore.load(fis, masterPassword.toCharArray()); } catch (Exception ex) { /* Clear out things that are useless/hindering now */ truststore = null; masterPassword = null; String exMessage = "Failed to load Taverna's Truststore from " + truststoreFile.getAbsolutePath() + ". Possible reason: incorrect password or corrupted file."; logger.error(exMessage, ex); throw new CMException(exMessage, ex); } deleteRevokedCertificates(); } else { /* * Otherwise create a new empty Truststore and load it with certs * from Java's truststore. */ File javaTruststoreFile = new File(System.getProperty("java.home"), "lib/security/cacerts"); KeyStore javaTruststore = null; // Java's truststore is of type "JKS" - try to load it try { javaTruststore = KeyStore.getInstance("JKS"); } catch (Exception ex) { // The requested keystore type is not available from the // provider throw new CMException( "Failed to instantiate a 'JKS'-type keystore " + "for reading Java's truststore.", ex); } boolean loadedJavaTruststore = false; /* * Load Java's truststore from the file - try with the default Java * truststore passwords. */ for (String password : defaultTrustStorePasswords) { logger.info("Trying to load Java truststore using password: " + password); try (FileInputStream fis = new FileInputStream(javaTruststoreFile)) { javaTruststore.load(fis, password.toCharArray()); loadedJavaTruststore = true; break; } catch (IOException ioex) { /* * If there is an I/O or format problem with the keystore * data, or if the given password was incorrect. (Thank you * Sun, now I can't know if it is the file or the * password..) */ logger.info(String.format( "Failed to load the Java truststore to copy " + "over certificates using default password: " + "%s from %s", password, javaTruststoreFile)); } catch (NoSuchAlgorithmException e) { logger.error("Unknown encryption algorithm " + "while loading Java truststore from " + javaTruststoreFile, e); break; } catch (CertificateException e) { logger.error("Certificate error while " + "loading Java truststore from " + javaTruststoreFile, e); break; } } /* * Default Java truststore passwords failed - possibly the user has * changed it. Ask the Java truststore password providers if they * can help - this will typically pop up a dialog to ask the user if * we are in a graphical environment. If not, we will simply not * copy the default truststore certificates into Credential * Manager's Truststore. */ if (!loadedJavaTruststore && !loadJavaTruststoreUsingPasswordProviders(javaTruststore, javaTruststoreFile)) { String error = "Credential manager failed to load" + " certificates from Java's truststore."; String help = "Try using the system property -D" + PROPERTY_TRUSTSTORE_PASSWORD + "=TheTrustStorePassword"; logger.error(error + " " + help); // FIXME Writes to standard error! System.err.println(error); System.err.println(help); } // Create a new empty Truststore for Taverna try (FileOutputStream fos = new FileOutputStream(truststoreFile)) { truststore.load(null, null); if (loadedJavaTruststore) { // Copy certificates into Taverna's Truststore from // Java's truststore. Enumeration<String> aliases = javaTruststore.aliases(); while (aliases.hasMoreElements()) { Certificate certificate = javaTruststore.getCertificate(aliases.nextElement()); if (certificate instanceof X509Certificate) truststore.setCertificateEntry( createTrustedCertificateAlias((X509Certificate) certificate), certificate); } } // Insert special trusted CA certificates logger.info( "Loading certificates of trusted CAs so as to establish trust into our services such as BioCatalogue, BiodiversityCatalogue, heater, etc."); CertificateFactory cf = CertificateFactory.getInstance("X.509"); for (URL trustedCertURL : getSpecialTrustedCertificates()) // Load the certificate (possibly a chain) from the // stream try (InputStream stream = trustedCertURL.openStream()) { for (Certificate c : cf.generateCertificates(stream)) truststore.setCertificateEntry(createTrustedCertificateAlias((X509Certificate) c), c); } catch (Exception cex) { logger.error("Failed to insert trusted certificate entry in the Truststore", cex); } // Immediately save the new Truststore to the file truststore.store(fos, masterPassword.toCharArray()); } catch (Exception ex) { /* * make truststore null as it was just created but failed to * save so we should retry next time */ truststore = null; throw new CMException("Failed to generate new empty Taverna's Truststore", ex); } } /* * Taverna distro for MAC contains info.plist file with some Java system * properties set to use the Keychain which clashes with what we are * setting here so we need to clear them. */ System.clearProperty(PROPERTY_TRUSTSTORE_TYPE); System.clearProperty(PROPERTY_TRUSTSTORE_PROVIDER); /* * Not quite sure why we still need to set these two properties since we * are creating our own SSLSocketFactory with our own TrustManager that * uses Taverna's Truststore, but seem like after Taverna starts up and * the first time it needs SSLSocketFactory for HTTPS connection it is * still using the default Java's truststore unless these properties are * set. Set the system property "javax.net.ssl.Truststore" to use * Taverna's truststore. */ /* * Axis 1 likes reading from these properties but seems to work as well * with Taverna's SSLSocetFactory as well. We do not want to expose * these as they can be read from Beanshells. */ // System.setProperty(PROPERTY_TRUSTSTORE, truststoreFile.getAbsolutePath()); // System.setProperty(PROPERTY_TRUSTSTORE_PASSWORD, masterPassword); System.clearProperty(PROPERTY_TRUSTSTORE); System.clearProperty(PROPERTY_TRUSTSTORE_PASSWORD); }
From source file:org.apache.taverna.security.credentialmanager.impl.CredentialManagerImpl.java
/** * Load Taverna's Truststore from a file on a disk. If the Truststore does * not already exist, a new empty one will be created and contents of Java's * truststore located in <JAVA_HOME>/lib/security/cacerts will be copied * over to the Truststore./*from w ww . j a v a2s. c om*/ */ private void loadTruststore() throws CMException { if (truststore == null) { try { // Try to create Taverna's Truststore as Bouncy Castle UBER-type // keystore. truststore = KeyStore.getInstance("UBER", "BC"); } catch (Exception ex) { // The requested keystore type is not available from security // providers. throw new CMException("Failed to instantiate Taverna's Truststore", ex); } if (truststoreFile.exists()) { // If the Truststore file already exists, open it and load the // Truststore try (FileInputStream fis = new FileInputStream(truststoreFile)) { // Load the Truststore from the file truststore.load(fis, masterPassword.toCharArray()); // Delete the old revoked or unnecessary BioCatalogue, // BiodiversityCatalogue and heater's certificates, if present deleteRevokedCertificates(); } catch (Exception ex) { /* Clear out things that are useless/hindering now */ truststore = null; masterPassword = null; String exMessage = "Failed to load Taverna's Truststore from " + truststoreFile.getAbsolutePath() + ". Possible reason: incorrect password or corrupted file."; logger.error(exMessage, ex); throw new CMException(exMessage, ex); } } else { /* * Otherwise create a new empty Truststore and load it with * certs from Java's truststore. */ File javaTruststoreFile = new File(System.getProperty("java.home"), "lib/security/cacerts"); KeyStore javaTruststore = null; // Java's truststore is of type "JKS" - try to load it try { javaTruststore = KeyStore.getInstance("JKS"); } catch (Exception ex) { // The requested keystore type is not available from the // provider throw new CMException( "Failed to instantiate a 'JKS'-type keystore " + "for reading Java's truststore.", ex); } boolean loadedJavaTruststore = false; /* * Load Java's truststore from the file - try with the default * Java truststore passwords. */ for (String password : defaultTrustStorePasswords) { logger.info("Trying to load Java truststore using password: " + password); try (FileInputStream fis = new FileInputStream(javaTruststoreFile)) { javaTruststore.load(fis, password.toCharArray()); loadedJavaTruststore = true; break; } catch (IOException ioex) { /* * If there is an I/O or format problem with the * keystore data, or if the given password was incorrect * (Thank you Sun, now I can't know if it is the file or * the password..) */ logger.info(String.format( "Failed to load the Java truststore to copy " + "over certificates using default password: " + "%s from %s", password, javaTruststoreFile)); } catch (NoSuchAlgorithmException e) { logger.error("Unknown encryption algorithm " + "while loading Java truststore from " + javaTruststoreFile, e); break; } catch (CertificateException e) { logger.error( "Certificate error while " + "loading Java truststore from " + javaTruststoreFile, e); break; } } /* * Default Java truststore passwords failed - possibly the user * has changed it. Ask the Java truststore password providers if * they can help - this will typically pop up a dialog to ask * the user if we are in a graphical environment. If not, we * will simply not copy the default truststore certificates into * Credential Manager's Truststore. */ if (!loadedJavaTruststore) if (!(loadJavaTruststoreUsingPasswordProviders(javaTruststore, javaTruststoreFile))) { String error = "Credential manager failed to load" + " certificates from Java's truststore."; String help = "Try using the system property -D" + PROPERTY_TRUSTSTORE_PASSWORD + "=TheTrustStorePassword"; logger.error(error + " " + help); // FIXME Writes to standard error! System.err.println(error); System.err.println(help); } // Create a new empty Truststore for Taverna try (FileOutputStream fos = new FileOutputStream(truststoreFile)) { truststore.load(null, null); if (loadedJavaTruststore) { // Copy certificates into Taverna's Truststore from // Java's truststore. Enumeration<String> aliases = javaTruststore.aliases(); while (aliases.hasMoreElements()) { Certificate certificate = javaTruststore.getCertificate(aliases.nextElement()); if (certificate instanceof X509Certificate) truststore.setCertificateEntry( createTrustedCertificateAlias((X509Certificate) certificate), certificate); } } // Insert special trusted CA certificates logger.info( "Loading certificates of trusted CAs so as to establish trust into our services such as BioCatalogue, BiodiversityCatalogue, heater, etc."); CertificateFactory cf = CertificateFactory.getInstance("X.509"); for (URL trustedCertURL : getSpecialTrustedCertificates()) // Load the certificate (possibly a chain) from the // stream try (InputStream stream = trustedCertURL.openStream()) { for (Certificate c : cf.generateCertificates(stream)) truststore.setCertificateEntry(createTrustedCertificateAlias((X509Certificate) c), c); } catch (Exception cex) { logger.error("Failed to insert trusted certificate entry in the Truststore", cex); } // Immediately save the new Truststore to the file truststore.store(fos, masterPassword.toCharArray()); } catch (Exception ex) { /* * make truststore null as it was just created but failed to * save so we should retry next time */ truststore = null; throw new CMException("Failed to generate new empty Taverna's Truststore", ex); } } /* * Taverna distro for MAC contains info.plist file with some Java * system properties set to use the Keychain which clashes with what * we are setting here so we need to clear them. */ System.clearProperty(PROPERTY_TRUSTSTORE_TYPE); System.clearProperty(PROPERTY_TRUSTSTORE_PROVIDER); /* * Not quite sure why we still need to set these two properties * since we are creating our own SSLSocketFactory with our own * TrustManager that uses Taverna's Truststore, but seem like after * Taverna starts up and the first time it needs SSLSocketFactory * for HTTPS connection it is still using the default Java's * truststore unless these properties are set. Set the system * property "javax.net.ssl.Truststore" to use Taverna's truststore. */ /* * Axis 1 likes reading from these properties but seems to work as * well with Taverna's SSLSocetFactory as well. We do not want to * expose these as they can be read from Beanshells. */ // System.setProperty(PROPERTY_TRUSTSTORE, truststoreFile.getAbsolutePath()); // System.setProperty(PROPERTY_TRUSTSTORE_PASSWORD, masterPassword); System.clearProperty(PROPERTY_TRUSTSTORE); System.clearProperty(PROPERTY_TRUSTSTORE_PASSWORD); } }