Example usage for java.security KeyStore aliases

List of usage examples for java.security KeyStore aliases

Introduction

In this page you can find the example usage for java.security KeyStore aliases.

Prototype

public final Enumeration<String> aliases() throws KeyStoreException 

Source Link

Document

Lists all the alias names of this keystore.

Usage

From source file:org.tolven.gatekeeper.CertificateHelper.java

public PrivateKey getPrivateKey(KeyStore keyStore, char[] password) {
    String alias = null;/*from  w  ww.  j av  a  2s.co m*/
    try {
        Enumeration<String> aliases = keyStore.aliases();
        if (!aliases.hasMoreElements()) {
            throw new RuntimeException("KeyStore contains no aliases");
        }
        alias = aliases.nextElement();
    } catch (KeyStoreException ex) {
        throw new RuntimeException("Could obtain alias: " + alias + " in the userPKCS12 keystore", ex);
    }
    try {
        return (PrivateKey) keyStore.getKey(alias, password);
    } catch (Exception ex) {
        throw new RuntimeException("Could not get PrivateKey from KeyStore using alias: " + alias, ex);
    }
}

From source file:be.fgov.kszbcss.rhq.websphere.connector.agent.ConnectorSubsystemComponent.java

public OperationResult invokeOperation(String name, Configuration parameters)
        throws InterruptedException, Exception {
    if (name.equals("importCertificateFromFile")) {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        InputStream in = new FileInputStream(parameters.getSimple("file").getStringValue());
        try {//from   www.java2  s  .  c  om
            Iterator<? extends Certificate> it = cf.generateCertificates(in).iterator();
            if (it.hasNext()) {
                TrustStoreManager.getInstance().addCertificate(parameters.getSimple("alias").getStringValue(),
                        (X509Certificate) it.next());
            } else {
                throw new Exception("No certificate found");
            }
        } finally {
            in.close();
        }
        return null;
    } else if (name.equals("retrieveCellCertificate")) {
        DeploymentManager dm = new DeploymentManager(null, new ConfigurationBasedProcessLocator(parameters));
        String cell = dm.getCell();
        ConfigQueryExecutor configQueryExecutor = ConfigQueryServiceFactory.getInstance()
                .getConfigQueryExecutor(dm);
        try {
            X509Certificate cert = configQueryExecutor.query(CellRootCertificateQuery.INSTANCE);
            TrustStoreManager.getInstance().addCertificate("cell:" + cell, cert);
        } finally {
            configQueryExecutor.destroy();
        }
        return null;
    } else if (name.equals("retrieveCertificateFromPort")) {
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(new KeyManager[0],
                new TrustManager[] {
                        new AutoImportTrustManager(parameters.getSimple("alias").getStringValue()) },
                new SecureRandom());
        SSLSocket socket = (SSLSocket) sslContext.getSocketFactory().createSocket(
                parameters.getSimple("host").getStringValue(), parameters.getSimple("port").getIntegerValue());
        try {
            socket.startHandshake();
        } finally {
            socket.close();
        }
        return null;
    } else if (name.equals("listCertificates")) {
        final PropertyList certificates = new PropertyList("certificates");
        TrustStoreManager.getInstance().execute(new TrustStoreAction() {
            public void execute(KeyStore truststore) throws Exception {
                // Sort the aliases for convenience
                Set<String> aliases = new TreeSet<String>();
                for (Enumeration<String> e = truststore.aliases(); e.hasMoreElements();) {
                    aliases.add(e.nextElement());
                }
                for (String alias : aliases) {
                    X509Certificate cert = (X509Certificate) truststore.getCertificate(alias);
                    PropertyMap map = new PropertyMap("certificate");
                    map.put(new PropertySimple("alias", alias));
                    map.put(new PropertySimple("subject", cert.getSubjectDN().toString()));
                    MessageDigest md = MessageDigest.getInstance("SHA-1");
                    md.update(cert.getEncoded());
                    byte[] digest = md.digest();
                    StringBuilder fingerprint = new StringBuilder();
                    for (int i = 0; i < digest.length; i++) {
                        if (i > 0) {
                            fingerprint.append(':');
                        }
                        fingerprint.append(getHexDigit(((int) digest[i] & 0xf0) >> 4));
                        fingerprint.append(getHexDigit((int) digest[i] & 0x0f));
                    }
                    map.put(new PropertySimple("fingerprint", fingerprint.toString()));
                    certificates.add(map);
                }
            }
        }, true);
        if (log.isDebugEnabled()) {
            log.debug("certificates=" + certificates);
        }
        OperationResult result = new OperationResult();
        result.getComplexResults().put(certificates);
        return result;
    } else if (name.equals("removeCertificate")) {
        final String alias = parameters.getSimple("alias").getStringValue();
        TrustStoreManager.getInstance().execute(new TrustStoreAction() {
            public void execute(KeyStore truststore) throws Exception {
                truststore.deleteEntry(alias);
            }
        }, false);
        return null;
    } else if (name.equals("renameCertificate")) {
        final String oldAlias = parameters.getSimple("oldAlias").getStringValue();
        final String newAlias = parameters.getSimple("newAlias").getStringValue();
        TrustStoreManager.getInstance().execute(new TrustStoreAction() {
            public void execute(KeyStore truststore) throws Exception {
                Certificate cert = truststore.getCertificate(oldAlias);
                truststore.setCertificateEntry(newAlias, cert);
                truststore.deleteEntry(oldAlias);
            }
        }, false);
        return null;
    } else {
        return null;
    }
}

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. j  a  v  a 2 s .co  m

    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:nl.clockwork.mule.ebms.cxf.EbMSSecSignatureInInterceptor.java

private boolean validateCertificate(KeyStore keyStore, X509Certificate certificate, Date date)
        throws KeyStoreException {
    try {//from w w w .java 2 s. c  o m
        certificate.checkValidity(date);
    } catch (Exception e) {
        return false;
    }
    Enumeration<String> aliases = keyStore.aliases();
    while (aliases.hasMoreElements()) {
        try {
            Certificate c = keyStore.getCertificate(aliases.nextElement());
            certificate.verify(c.getPublicKey());
            return true;
        } catch (KeyStoreException e) {
            throw e;
        } catch (Exception e) {
            logger.debug("", e);
        }
    }
    return false;
}

From source file:com.cloudera.nav.sdk.client.SSLUtilsTest.java

@Before
public void setUp() throws Exception {
    Map<String, Object> confMap = Maps.newHashMap();
    confMap.put(ClientConfigFactory.APP_URL, "localhost");
    confMap.put(ClientConfigFactory.NAV_URL, "localhost");
    confMap.put(ClientConfigFactory.NAMESPACE, "test");
    confMap.put(ClientConfigFactory.USERNAME, "user");
    confMap.put(ClientConfigFactory.PASSWORD, "pass");
    confMap.put(ClientConfigFactory.API_VERSION, 9);
    config = (new ClientConfigFactory()).fromConfigMap(confMap);

    KeyStore keyStore = KeyStore.getInstance("jks");
    ClassLoader classLoader = getClass().getClassLoader();
    String keyStoreLocation = classLoader.getResource("client.jks").getFile();
    try (InputStream is = new FileInputStream(keyStoreLocation)) {
        keyStore.load(is, "clientP".toCharArray());
    }/*ww w  .  j a v a  2 s  .c  o  m*/
    certs = Maps.newHashMap();
    Enumeration<String> aliasesEn = keyStore.aliases();
    String alias;
    while (aliasesEn.hasMoreElements()) {
        alias = aliasesEn.nextElement();
        certs.put(alias, keyStore.getCertificate(alias));
    }
}

From source file:org.codice.ddf.security.common.Security.java

/**
 * Gets the {@link Subject} associated with this system. Uses a cached subject since the subject
 * will not change between calls.//from   ww  w . j  a  va  2 s .c  om
 *
 * @return system's {@link Subject}
 */
public synchronized Subject getSystemSubject() {

    if (!tokenAboutToExpire(cachedSystemSubject)) {
        return cachedSystemSubject;
    }

    KeyStore keyStore = getSystemKeyStore();
    String alias = null;
    Certificate cert = null;
    try {
        if (keyStore != null) {
            if (keyStore.size() == 1) {
                alias = keyStore.aliases().nextElement();
            } else if (keyStore.size() > 1) {
                alias = getCertificateAlias();
            }
            cert = keyStore.getCertificate(alias);
        }
    } catch (KeyStoreException e) {
        LOGGER.error("Unable to get certificate for alias [{}]", alias, e);
        return null;
    }

    if (cert == null) {
        LOGGER.error("Unable to get certificate for alias [{}]", alias);
        return null;
    }

    PKIAuthenticationTokenFactory pkiTokenFactory = createPKITokenFactory();
    PKIAuthenticationToken pkiToken = pkiTokenFactory.getTokenFromCerts(
            new X509Certificate[] { (X509Certificate) cert }, PKIAuthenticationToken.DEFAULT_REALM);
    if (pkiToken != null) {
        SecurityManager securityManager = getSecurityManager();
        if (securityManager != null) {
            try {
                cachedSystemSubject = securityManager.getSubject(pkiToken);
            } catch (SecurityServiceException sse) {
                LOGGER.error("Unable to request subject for system user.", sse);
            }
        }
    }
    return cachedSystemSubject;
}

From source file:mitm.djigzo.web.pages.admin.SSLCertificateManager.java

public void onValidateForm() {
    if (password != null && file != null) {
        try {// www  .ja va 2  s  .  c  om
            KeyStore keyStore = getKeyStore();

            boolean keyFound = false;
            boolean validForSSL = true;

            Enumeration<String> aliases = keyStore.aliases();

            while (aliases.hasMoreElements()) {
                String alias = aliases.nextElement();

                if (keyStore.getKey(alias, null) != null) {
                    Certificate certificate = keyStore.getCertificate(alias);

                    if (!(certificate instanceof X509Certificate)) {
                        continue;
                    }

                    /*
                     * Check if the certificate is valid for SSL
                     */
                    X509CertificateInspector inspector = new X509CertificateInspector(
                            (X509Certificate) certificate);

                    Set<ExtendedKeyUsageType> extendedKeyUsage = inspector.getExtendedKeyUsage();

                    if (extendedKeyUsage != null
                            && !(extendedKeyUsage.contains(ExtendedKeyUsageType.ANYKEYUSAGE)
                                    || extendedKeyUsage.contains(ExtendedKeyUsageType.SERVERAUTH))) {
                        validForSSL = false;
                    }

                    Set<KeyUsageType> keyUsage = inspector.getKeyUsage();

                    if (keyUsage != null && !(keyUsage.contains(KeyUsageType.KEYAGREEMENT)
                            || keyUsage.contains(KeyUsageType.KEYENCIPHERMENT))) {
                        validForSSL = false;
                    }

                    keyFound = true;

                    break;
                }
            }

            if (!keyFound) {
                form.recordError(upload, "The PFX file does not contain a key.");
            } else {
                if (!validForSSL) {
                    form.recordError(upload, "The certificate contained in the PFX file is not valid for SSL");
                }
            }
        } catch (Exception e) {
            /*
             * loading a PFX can sometime result in a ClassCastException so we catch Exception.
             */
            form.recordError(upload, "The PFX file could not be read. Message: " + e.getMessage());

            logger.error("File is not a valid PFX file.", e);
        }
    }
}

From source file:com.sshtools.j2ssh.authentication.UserGridCredential.java

private static GSSCredential retrieveRemoteProxy(SshConnectionProperties properties, int proxyType,
        int lifetimeHours) throws IOException {
    GSSCredential gsscredential = null;
    CoGProperties cogproperties = CoGProperties.getDefault();

    String hostname = DEFAULT_MYPROXY_SERVER;
    hostname = PreferencesStore.get(SshTerminalPanel.PREF_DEFAULT_MYPROXY_HOSTNAME, hostname);
    String username = System.getProperty("user.name");
    username = PreferencesStore.get(SshTerminalPanel.PREF_MYPROXY_UNAME, username);

    if (properties instanceof SshToolsConnectionProfile) {
        SshToolsConnectionProfile profile = (SshToolsConnectionProfile) properties;
        hostname = profile.getApplicationProperty(SshTerminalPanel.PREF_DEFAULT_MYPROXY_HOSTNAME, hostname);
        username = profile.getApplicationProperty(SshTerminalPanel.PREF_MYPROXY_UNAME, username);
    }/*  w w  w  .  j a  v a2 s  .co  m*/

    do {
        boolean flag = false;
        StringBuffer stringbuffer = new StringBuffer();
        StringBuffer stringbuffer1 = new StringBuffer();
        StringBuffer stringbuffer2 = new StringBuffer();
        if (myProxyPrompt != null) {

            myProxyPrompt.setHost(hostname);
            myProxyPrompt.setAccountName(username);

            boolean flag1 = myProxyPrompt.doGet(properties.getWindow(), stringbuffer, stringbuffer1,
                    stringbuffer2);
            myProxyPrompt.setError("");
            if (flag1)
                throw new IOException("Canceled by user.");
            if (myProxyPrompt.getAnother())
                return null;

            StringBuffer stringbufferF = new StringBuffer();
            StringBuffer stringbufferP = new StringBuffer();
            if (myProxyPrompt.getBrowser()) {
                gsscredential = chooseCert(proxyType, lifetimeHours, properties);
                if (gsscredential == null)
                    continue;
                else
                    return gsscredential;
            }
            if (myProxyPrompt.keyBased(stringbufferF, stringbufferP)) {
                try {
                    KeyStore store = null;
                    String passphrase = stringbufferP.toString();
                    File keyfile = new File(stringbufferF.toString());
                    Security.addProvider(new BouncyCastleProvider());
                    store = KeyStore.getInstance("PKCS12", "BC");
                    FileInputStream in = new FileInputStream(keyfile);
                    store.load(in, passphrase.toCharArray());

                    Enumeration e = store.aliases();
                    if (!e.hasMoreElements()) {
                        JOptionPane.showMessageDialog(properties.getWindow(),
                                "Could not access your certificate: no certificates found in file.",
                                "GSI-SSHTerm Authentication", JOptionPane.ERROR_MESSAGE);
                        continue;
                    }
                    String alias = (String) e.nextElement();
                    java.security.cert.Certificate cert = store.getCertificate(alias);
                    Key key = store.getKey(alias, passphrase.toCharArray());

                    if (!(cert instanceof X509Certificate)) {
                        JOptionPane.showMessageDialog(properties.getWindow(),
                                "Could not access your certificate: bad certificate type.",
                                "GSI-SSHTerm Authentication", JOptionPane.ERROR_MESSAGE);
                        continue;
                    }
                    if (!(key instanceof PrivateKey)) {
                        JOptionPane.showMessageDialog(properties.getWindow(),
                                "Could not access your certificate: bad key type.",
                                "GSI-SSHTerm Authentication", JOptionPane.ERROR_MESSAGE);
                        continue;
                    }

                    BouncyCastleCertProcessingFactory factory = BouncyCastleCertProcessingFactory.getDefault();

                    GlobusCredential globuscredential = factory.createCredential(
                            new X509Certificate[] { (X509Certificate) cert }, (PrivateKey) key,
                            cogproperties.getProxyStrength(), lifetimeHours * 3600, proxyType,
                            (X509ExtensionSet) null);

                    if (globuscredential != null) {
                        if (SAVE_PKCS12_PROXY) {
                            ProxyHelper.saveProxy(globuscredential, properties);
                        }
                        try {
                            globuscredential.verify();
                            gsscredential = new GlobusGSSCredentialImpl(globuscredential, 1);
                        } catch (Exception exception1) {
                            exception1.printStackTrace();
                            StringWriter stringwriter1 = new StringWriter();
                            exception1.printStackTrace(new PrintWriter(stringwriter1));
                            log.debug(stringwriter1);
                            if (exception1.getMessage().indexOf("Expired credentials") >= 0) {
                                JOptionPane.showMessageDialog(properties.getWindow(),
                                        "Your certificate has expired, please renew your certificate or try another method for authentication.",
                                        "GSI-SSHTerm Authentication", JOptionPane.ERROR_MESSAGE);
                                continue;
                            } else {
                                errorReport(properties.getWindow(), "Could not load your certificate",
                                        exception1);
                                continue;
                            }
                        }

                    }
                    return gsscredential;
                } catch (java.io.FileNotFoundException exception) {
                    exception.printStackTrace();
                    StringWriter stringwriter = new StringWriter();
                    exception.printStackTrace(new PrintWriter(stringwriter));
                    log.debug(stringwriter);
                    myProxyPrompt.setError("Certificate: could not find file");
                    continue;
                } catch (Exception exception) {
                    if (exception.getMessage().indexOf("Illegal key size") >= 0) {
                        exception.printStackTrace();
                        StringWriter stringwriter = new StringWriter();
                        exception.printStackTrace(new PrintWriter(stringwriter));
                        log.debug(stringwriter);
                        errorReport(properties.getWindow(),
                                "To use this PKCS#12 file you need to install the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files\n (see http://java.sun.com/javase/downloads/index.jsp for Java 6 and http://java.sun.com/javase/downloads/index_jdk5.jsp for Java 5)",
                                exception);
                        continue;
                    } else if (exception.getMessage().indexOf("wrong password") >= 0) {
                        exception.printStackTrace();
                        StringWriter stringwriter = new StringWriter();
                        exception.printStackTrace(new PrintWriter(stringwriter));
                        log.debug(stringwriter);
                        myProxyPrompt.setError("Certificate: wrong password?");
                        continue;
                    } else {
                        exception.printStackTrace();
                        StringWriter stringwriter = new StringWriter();
                        exception.printStackTrace(new PrintWriter(stringwriter));
                        log.debug(stringwriter);
                        errorReport(properties.getWindow(), "Unknown problem while loading your certificate",
                                exception);
                        continue;
                    }
                }
            }
        }
        CertUtil.init();
        // save username if changed:
        if (!stringbuffer1.toString().equals(username)) {
            PreferencesStore.put(SshTerminalPanel.PREF_LAST_MYPROXY_USERNAME, stringbuffer1.toString());
        }
        String port_S = DEFAULT_MYPROXY_PORT;
        port_S = PreferencesStore.get(SshTerminalPanel.PREF_MYPROXY_PORT, port_S);
        if (properties instanceof SshToolsConnectionProfile) {
            SshToolsConnectionProfile profile = (SshToolsConnectionProfile) properties;
            port_S = profile.getApplicationProperty(SshTerminalPanel.PREF_MYPROXY_PORT, port_S);
        }
        int port = 7512;
        try {
            port = Integer.parseInt(port_S);
        } catch (NumberFormatException e) {
            log.warn("Could not parse the port number from defaults file (property name"
                    + SshTerminalPanel.PREF_MYPROXY_PORT + ", property value= " + port_S + ").");
        }
        MyProxy myproxy = null;
        myproxy = new MyProxy(stringbuffer.toString(), port);
        try {
            gsscredential = myproxy.get(null, stringbuffer1.toString(), stringbuffer2.toString(),
                    lifetimeHours * 3600);

            if (SAVE_MYPROXY_PROXY) {
                GlobusCredential proxy = ((GlobusGSSCredentialImpl) gsscredential).getGlobusCredential();
                ProxyHelper.saveProxy(proxy, properties);
            }
            log.debug("A proxy has been received for user " + stringbuffer1);
            return gsscredential;
        } catch (Exception exception) {
            if (exception.getMessage().indexOf("Credentials do not exist") >= 0) {
                exception.printStackTrace();
                StringWriter stringwriter = new StringWriter();
                exception.printStackTrace(new PrintWriter(stringwriter));
                log.debug(stringwriter);
                myProxyPrompt.setError("MyProxy: No credentials on server (wrong username?)");
            } else if (exception.getMessage().indexOf("Bad password") >= 0) {
                exception.printStackTrace();
                StringWriter stringwriter = new StringWriter();
                exception.printStackTrace(new PrintWriter(stringwriter));
                log.debug(stringwriter);
                myProxyPrompt.setError("MyProxy: Bad username and/or password");
            } else if (exception.getMessage()
                    .indexOf("Failed to map username too DN via grid-mapfile CA failed to map user") >= 0) {
                exception.printStackTrace();
                StringWriter stringwriter = new StringWriter();
                exception.printStackTrace(new PrintWriter(stringwriter));
                log.debug(stringwriter);
                myProxyPrompt.setError("MyProxy: Bad username/password");
            } else if (exception.getMessage().indexOf("PAM authentication failed") >= 0) {
                exception.printStackTrace();
                StringWriter stringwriter = new StringWriter();
                exception.printStackTrace(new PrintWriter(stringwriter));
                log.debug(stringwriter);
                myProxyPrompt.setError("MyProxy: Bad username/password");
            } else if (exception.getMessage().indexOf("credentials have expired") >= 0) {
                exception.printStackTrace();
                StringWriter stringwriter = new StringWriter();
                exception.printStackTrace(new PrintWriter(stringwriter));
                log.debug(stringwriter);
                myProxyPrompt.setError("MyProxy: Credentials on server has expired");
            } else if (exception.getMessage().indexOf(stringbuffer.toString()) >= 0) {
                exception.printStackTrace();
                StringWriter stringwriter = new StringWriter();
                exception.printStackTrace(new PrintWriter(stringwriter));
                log.debug(stringwriter);
                myProxyPrompt.setError("MyProxy: Could not connect to MyProxy server");
            } else if (exception.getMessage().indexOf("Password must be at least 6 characters long") >= 0) {
                exception.printStackTrace();
                StringWriter stringwriter = new StringWriter();
                exception.printStackTrace(new PrintWriter(stringwriter));
                log.debug(stringwriter);
                myProxyPrompt.setError("MyProxy: Password must be at least 6 characters long.");
            } else {
                exception.printStackTrace();
                StringWriter stringwriter = new StringWriter();
                exception.printStackTrace(new PrintWriter(stringwriter));
                log.debug(stringwriter);
                errorReport(properties.getWindow(), "Unknown problem while accessing MyProxy", exception);
                continue;
            }
        }
    } while (true);
}

From source file:org.apache.commons.httpclient.contrib.ssl.AuthSSLProtocolSocketFactory.java

private SSLContext createSSLContext() {
    try {//from  w  w  w .j a v  a 2  s . co m
        KeyManager[] keymanagers = null;
        TrustManager[] trustmanagers = null;
        if (this.keystoreUrl != null) {
            KeyStore keystore = createKeyStore(this.keystoreUrl, this.keystorePassword);
            if (LOG.isDebugEnabled()) {
                Enumeration aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = (String) aliases.nextElement();
                    Certificate[] certs = keystore.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.debug(" Certificate " + (c + 1) + ":");
                                LOG.debug("  Subject DN: " + cert.getSubjectDN());
                                LOG.debug("  Signature Algorithm: " + cert.getSigAlgName());
                                LOG.debug("  Valid from: " + cert.getNotBefore());
                                LOG.debug("  Valid until: " + cert.getNotAfter());
                                LOG.debug("  Issuer: " + cert.getIssuerDN());
                            }
                        }
                    }
                }
            }
            keymanagers = createKeyManagers(keystore, this.keystorePassword);
        }
        if (this.truststoreUrl != null) {
            KeyStore keystore = createKeyStore(this.truststoreUrl, this.truststorePassword);
            if (LOG.isDebugEnabled()) {
                Enumeration aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = (String) aliases.nextElement();
                    LOG.debug("Trusted certificate '" + alias + "':");
                    Certificate trustedcert = keystore.getCertificate(alias);
                    if (trustedcert != null && trustedcert instanceof X509Certificate) {
                        X509Certificate cert = (X509Certificate) trustedcert;
                        LOG.debug("  Subject DN: " + cert.getSubjectDN());
                        LOG.debug("  Signature Algorithm: " + cert.getSigAlgName());
                        LOG.debug("  Valid from: " + cert.getNotBefore());
                        LOG.debug("  Valid until: " + cert.getNotAfter());
                        LOG.debug("  Issuer: " + cert.getIssuerDN());
                    }
                }
            }
            trustmanagers = createTrustManagers(keystore);
        }
        SSLContext sslcontext = SSLContext.getInstance("SSL");
        sslcontext.init(keymanagers, trustmanagers, null);
        return sslcontext;
    } catch (NoSuchAlgorithmException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Unsupported algorithm exception: " + e.getMessage());
    } catch (KeyStoreException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Keystore exception: " + e.getMessage());
    } catch (GeneralSecurityException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Key management exception: " + e.getMessage());
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("I/O error reading keystore/truststore file: " + e.getMessage());
    }
}

From source file:se.inera.axel.shs.client.AuthSSLProtocolSocketFactory.java

private SSLContext createSSLContext() {
    try {//ww  w . j  a  va 2  s .c om
        KeyManager[] keymanagers = null;
        TrustManager[] trustmanagers = null;
        if (this.keystoreUrl != null) {
            KeyStore keystore = createKeyStore(this.keystoreUrl, this.keystorePassword);
            if (LOG.isDebugEnabled()) {
                Enumeration aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = (String) aliases.nextElement();
                    Certificate[] certs = keystore.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.debug(" Certificate " + (c + 1) + ":");
                                LOG.debug("  Subject DN: " + cert.getSubjectDN());
                                LOG.debug("  Signature Algorithm: " + cert.getSigAlgName());
                                LOG.debug("  Valid from: " + cert.getNotBefore());
                                LOG.debug("  Valid until: " + cert.getNotAfter());
                                LOG.debug("  Issuer: " + cert.getIssuerDN());
                            }
                        }
                    }
                }
            }
            keymanagers = createKeyManagers(keystore, this.keystorePassword);
        }
        if (this.truststoreUrl != null) {
            KeyStore keystore = createKeyStore(this.truststoreUrl, this.truststorePassword);
            if (LOG.isDebugEnabled()) {
                Enumeration aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = (String) aliases.nextElement();
                    LOG.debug("Trusted certificate '" + alias + "':");
                    Certificate trustedcert = keystore.getCertificate(alias);
                    if (trustedcert != null && trustedcert instanceof X509Certificate) {
                        X509Certificate cert = (X509Certificate) trustedcert;
                        LOG.debug("  Subject DN: " + cert.getSubjectDN());
                        LOG.debug("  Signature Algorithm: " + cert.getSigAlgName());
                        LOG.debug("  Valid from: " + cert.getNotBefore());
                        LOG.debug("  Valid until: " + cert.getNotAfter());
                        LOG.debug("  Issuer: " + cert.getIssuerDN());
                    }
                }
            }
            trustmanagers = createTrustManagers(keystore);
        }
        SSLContext sslcontext = SSLContext.getInstance("TLSv1");
        sslcontext.init(keymanagers, trustmanagers, null);
        return sslcontext;
    } catch (NoSuchAlgorithmException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Unsupported algorithm exception: " + e.getMessage());
    } catch (KeyStoreException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Keystore exception: " + e.getMessage());
    } catch (GeneralSecurityException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Key management exception: " + e.getMessage());
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("I/O error reading keystore/truststore file: " + e.getMessage());
    }
}