Example usage for java.security KeyStore getCertificate

List of usage examples for java.security KeyStore getCertificate

Introduction

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

Prototype

public final Certificate getCertificate(String alias) throws KeyStoreException 

Source Link

Document

Returns the certificate associated with the given alias.

Usage

From source file:com.predic8.membrane.core.transport.ssl.SSLContext.java

public SSLContext(SSLParser sslParser, ResolverMap resourceResolver, String baseLocation) {
    this.sslParser = sslParser;
    try {/*from w w w . ja v  a2 s.  c o  m*/
        String algorihm = KeyManagerFactory.getDefaultAlgorithm();
        if (sslParser.getAlgorithm() != null)
            algorihm = sslParser.getAlgorithm();

        KeyManagerFactory kmf = null;
        String keyStoreType = "JKS";
        if (sslParser.getKeyStore() != null) {
            if (sslParser.getKeyStore().getKeyAlias() != null)
                throw new InvalidParameterException("keyAlias is not yet supported.");
            char[] keyPass = "changeit".toCharArray();
            if (sslParser.getKeyStore().getKeyPassword() != null)
                keyPass = sslParser.getKeyStore().getKeyPassword().toCharArray();

            if (sslParser.getKeyStore().getType() != null)
                keyStoreType = sslParser.getKeyStore().getType();
            KeyStore ks = openKeyStore(sslParser.getKeyStore(), "JKS", keyPass, resourceResolver, baseLocation);
            kmf = KeyManagerFactory.getInstance(algorihm);
            kmf.init(ks, keyPass);

            Enumeration<String> aliases = ks.aliases();
            while (aliases.hasMoreElements()) {
                String alias = aliases.nextElement();
                if (ks.isKeyEntry(alias)) {
                    // first key is used by the KeyManagerFactory
                    Certificate c = ks.getCertificate(alias);
                    if (c instanceof X509Certificate) {
                        X509Certificate x = (X509Certificate) c;

                        dnsNames = new ArrayList<String>();

                        Collection<List<?>> subjectAlternativeNames = x.getSubjectAlternativeNames();
                        if (subjectAlternativeNames != null)
                            for (List<?> l : subjectAlternativeNames) {
                                if (l.get(0) instanceof Integer && ((Integer) l.get(0) == 2))
                                    dnsNames.add(l.get(1).toString());
                            }
                    }
                    break;
                }
            }

        }
        TrustManagerFactory tmf = null;
        if (sslParser.getTrustStore() != null) {
            String trustAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
            if (sslParser.getTrustStore().getAlgorithm() != null)
                trustAlgorithm = sslParser.getTrustStore().getAlgorithm();
            KeyStore ks = openKeyStore(sslParser.getTrustStore(), keyStoreType, null, resourceResolver,
                    baseLocation);
            tmf = TrustManagerFactory.getInstance(trustAlgorithm);
            tmf.init(ks);
        }

        TrustManager[] tms = tmf != null ? tmf.getTrustManagers()
                : null /* trust anyone: new TrustManager[] { new NullTrustManager() } */;
        if (sslParser.isIgnoreTimestampCheckFailure())
            tms = new TrustManager[] { new TrustManagerWrapper(tms, true) };

        if (sslParser.getProtocol() != null)
            sslc = javax.net.ssl.SSLContext.getInstance(sslParser.getProtocol());
        else
            sslc = javax.net.ssl.SSLContext.getInstance("TLS");

        sslc.init(kmf != null ? kmf.getKeyManagers() : null, tms, null);

        if (sslParser.getCiphers() != null) {
            ciphers = sslParser.getCiphers().split(",");
            Set<String> supportedCiphers = Sets.newHashSet(sslc.getSocketFactory().getSupportedCipherSuites());
            for (String cipher : ciphers) {
                if (!supportedCiphers.contains(cipher))
                    throw new InvalidParameterException("Unknown cipher " + cipher);
                if (cipher.contains("_RC4_"))
                    log.warn("Cipher " + cipher + " uses RC4, which is deprecated.");
            }
        } else {
            // use all default ciphers except those using RC4
            String supportedCiphers[] = sslc.getSocketFactory().getDefaultCipherSuites();
            ArrayList<String> ciphers = new ArrayList<String>(supportedCiphers.length);
            for (String cipher : supportedCiphers)
                if (!cipher.contains("_RC4_"))
                    ciphers.add(cipher);
            sortCiphers(ciphers);
            this.ciphers = ciphers.toArray(new String[ciphers.size()]);
        }
        if (setUseCipherSuitesOrderMethod == null)
            log.warn(
                    "Cannot set the cipher suite order before Java 8. This prevents Forward Secrecy with some SSL clients.");

        if (sslParser.getProtocols() != null) {
            protocols = sslParser.getProtocols().split(",");
        } else {
            protocols = null;
        }

        if (sslParser.getClientAuth() == null) {
            needClientAuth = false;
            wantClientAuth = false;
        } else if (sslParser.getClientAuth().equals("need")) {
            needClientAuth = true;
            wantClientAuth = true;
        } else if (sslParser.getClientAuth().equals("want")) {
            needClientAuth = false;
            wantClientAuth = true;
        } else {
            throw new RuntimeException("Invalid value '" + sslParser.getClientAuth()
                    + "' in clientAuth: expected 'want', 'need' or not set.");
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.googlecode.onevre.utils.ServerClassLoader.java

private boolean verifyCertificate(X509Certificate cert) {
    try {/*from ww w.j a v a  2  s  .  com*/
        String keypass = "";
        String keystorename = System.getProperty("deployment.user.security.trusted.certs");
        if (keystorename == null) {
            throw new IOException("No trusted certs keystore");
        }

        KeyStore keystore = KeyStore.getInstance("JKS", "SUN");
        File file = new File(keystorename);
        if (!file.exists()) {
            keystore.load(null, keypass.toCharArray());
        } else {
            keystore.load(new FileInputStream(keystorename), keypass.toCharArray());
        }
        boolean isInStore = false;
        Enumeration<String> aliases = keystore.aliases();
        while (aliases.hasMoreElements() && !isInStore) {
            String alias = aliases.nextElement();
            Certificate certificate = keystore.getCertificate(alias);
            if (certificate != null) {
                if (certificate.equals(cert)) {
                    isInStore = true;
                }
            }
        }
        if (!isInStore) {
            int result = JOptionPane.showConfirmDialog(null,
                    "Do you want to trust the bridge implementation " + "signed by\n"
                            + cert.getSubjectX500Principal().getName(),
                    "Trust source?", JOptionPane.YES_NO_OPTION);
            if (result == JOptionPane.YES_OPTION) {
                keystore.setEntry("deploymentusercert-" + System.currentTimeMillis(),
                        new KeyStore.TrustedCertificateEntry(cert), null);
                FileOutputStream output = new FileOutputStream(keystorename);
                keystore.store(output, keypass.toCharArray());
                output.close();
                return true;
            }
            return false;
        }
        return true;
    } catch (Throwable t) {
        t.printStackTrace();
    }
    return false;
}

From source file:org.wso2.carbon.dataservices.core.auth.JWTAuthorizationProvider.java

/**
 * Get the alias for the X509 certificate thumb
 * @param thumb/*from   ww w  . j a  va  2 s.c  o m*/
 * @param keyStore
 * @return
 * @throws org.apache.axis2.AxisFault
 */
private String getAliasForX509CertThumb(byte[] thumb, KeyStore keyStore) throws AxisFault {
    Certificate cert = null;
    MessageDigest sha = null;

    try {
        sha = MessageDigest.getInstance("SHA-1");
    } catch (NoSuchAlgorithmException e1) {
        log.error("noSHA1availabe");
        throw new AxisFault("noSHA1availabe");
    }
    try {
        for (Enumeration<String> e = keyStore.aliases(); e.hasMoreElements();) {
            String alias = (String) e.nextElement();
            Certificate[] certs = keyStore.getCertificateChain(alias);
            if (certs == null || certs.length == 0) {
                // no cert chain, so lets check if getCertificate gives us a result.
                cert = keyStore.getCertificate(alias);
                if (cert == null) {
                    return null;
                }
            } else {
                cert = certs[0];
            }
            if (!(cert instanceof X509Certificate)) {
                continue;
            }
            sha.reset();
            try {
                sha.update(cert.getEncoded());
            } catch (CertificateEncodingException e1) {
                log.error("Error encoding certificate");
                throw new AxisFault("Error encoding certificate");
            }
            byte[] data = sha.digest();
            if (new String(thumb).equals(hexify(data))) {
                return alias;
            }
        }
    } catch (KeyStoreException e) {
        log.error("KeyStore exception while getting alias for X509CertThumb");
        throw new AxisFault("KeyStore exception while getting alias for X509CertThumb");
    }
    return null;
}

From source file:org.wso2.carbon.appmgt.impl.token.JWTGenerator.java

/**
   * Helper method to add public certificate to JWT_HEADER to signature verification.
   *//from  w w  w. j a  va2 s  . co  m
   * @param endUserName
   * @throws org.wso2.carbon.appmgt.api.AppManagementException
   */
private String addCertToHeader(String endUserName) throws AppManagementException {

    try {
        //get tenant domain
        String tenantDomain = MultitenantUtils.getTenantDomain(endUserName);
        //get tenantId
        int tenantId = getTenantId(endUserName);
        Certificate publicCert = null;

        if (!(publicCerts.containsKey(tenantId))) {
            //get tenant's key store manager
            AppManagerUtil.loadTenantRegistry(tenantId);
            KeyStoreManager tenantKSM = KeyStoreManager.getInstance(tenantId);

            KeyStore keyStore = null;
            if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
                //derive key store name
                String ksName = tenantDomain.trim().replace(".", "-");
                String jksName = ksName + ".jks";
                keyStore = tenantKSM.getKeyStore(jksName);
                publicCert = keyStore.getCertificate(tenantDomain);
            } else {
                keyStore = tenantKSM.getPrimaryKeyStore();
                publicCert = tenantKSM.getDefaultPrimaryCertificate();
            }
            if (publicCert != null) {
                publicCerts.put(tenantId, publicCert);
            }
        } else {
            publicCert = publicCerts.get(tenantId);
        }

        //generate the SHA-1 thumbprint of the certificate
        //TODO: maintain a hashmap with tenants' pubkey thumbprints after first initialization
        MessageDigest digestValue = MessageDigest.getInstance("SHA-1");
        byte[] der = publicCert.getEncoded();
        digestValue.update(der);
        byte[] digestInBytes = digestValue.digest();

        String publicCertThumbprint = hexify(digestInBytes);
        String base64EncodedThumbPrint = Base64Utils.encode(publicCertThumbprint.getBytes());
        //String headerWithCertThumb = JWT_HEADER.replaceAll("\\[1\\]", base64EncodedThumbPrint);
        //headerWithCertThumb = headerWithCertThumb.replaceAll("\\[2\\]", signatureAlgorithm);
        //return headerWithCertThumb;

        StringBuilder jwtHeader = new StringBuilder();
        //Sample header
        //{"typ":"JWT", "alg":"SHA256withRSA", "x5t":"NmJmOGUxMzZlYjM2ZDRhNTZlYTA1YzdhZTRiOWE0NWI2M2JmOTc1ZA=="}
        //{"typ":"JWT", "alg":"[2]", "x5t":"[1]"}
        jwtHeader.append("{\"typ\":\"JWT\",");
        jwtHeader.append("\"alg\":\"");
        jwtHeader.append(signatureAlgorithm);
        jwtHeader.append("\",");

        jwtHeader.append("\"x5t\":\"");
        jwtHeader.append(base64EncodedThumbPrint);
        jwtHeader.append("\"");

        jwtHeader.append("}");
        return jwtHeader.toString();

    } catch (KeyStoreException e) {
        String error = "Error in obtaining tenant's keystore";
        throw new AppManagementException(error);
    } catch (CertificateEncodingException e) {
        String error = "Error in generating public cert thumbprint";
        throw new AppManagementException(error);
    } catch (NoSuchAlgorithmException e) {
        String error = "Error in generating public cert thumbprint";
        throw new AppManagementException(error);
    } catch (Exception e) {
        String error = "Error in obtaining tenant's keystore";
        throw new AppManagementException(error);
    }
}

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);
    }// ww  w  .j ava2s. c  o  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:test.integ.be.fedict.commons.eid.client.JCATest.java

@Test
public void testAutoFindCard() throws Exception {
    Security.addProvider(new BeIDProvider());

    final KeyStore keyStore = KeyStore.getInstance("BeID");
    BeIDKeyStoreParameter beIDKeyStoreParameter = new BeIDKeyStoreParameter();
    beIDKeyStoreParameter.setLocale(new Locale("fr"));
    keyStore.load(beIDKeyStoreParameter);

    final Enumeration<String> aliases = keyStore.aliases();
    assertNotNull(aliases);/*from w ww . j  a  va  2 s.c  om*/
    while (aliases.hasMoreElements()) {
        final String alias = aliases.nextElement();
        LOG.debug("alias: " + alias);
    }

    final X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");
    assertNotNull(authnCertificate);
}

From source file:org.objectweb.proactive.extensions.ssl.KeyStoreCreator.java

private boolean verify(String keyStore) {
    // Load the keystore
    FileInputStream fis = null;/*from   ww w .j  av  a  2 s .  c  o  m*/
    try {
        fis = new FileInputStream(keyStore);
    } catch (FileNotFoundException e) {
        System.err.println("Failed to open the key store: " + e);
        return false;
    }

    KeyStore ks = null;
    try {
        ks = KeyStore.getInstance("PKCS12", SslHelpers.BC_NAME);
        ks.load(fis, SslHelpers.DEFAULT_KS_PASSWD.toCharArray());
    } catch (Exception e) {
        System.err.println("Failed to open the key store: " + e);
        return false;
    }

    try {

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

        List<Certificate> matchingCerts = new LinkedList<Certificate>();
        List<Certificate> otherCerts = new LinkedList<Certificate>();

        while (aliases.hasMoreElements()) {
            String alias = (String) aliases.nextElement();
            //                if (ks.isCertificateEntry(alias)) {
            if (alias.matches(SslHelpers.DEFAULT_ALIAS_PATTERN)) {
                matchingCerts.add(ks.getCertificate(alias));
            } else {
                otherCerts.add(ks.getCertificate(alias));
            }
            //                }

            if (matchingCerts.size() > 0) {
                System.out.println(matchingCerts.size() + " matching certificate found");
                for (Certificate cert : matchingCerts) {
                    System.out.println(cert);
                }
            } else {
                System.err.println("No matching certificate foud. " + otherCerts.size()
                        + " non matching certificate found.");
                return false;
            }
        }
    } catch (KeyStoreException e) {
        // Should not happen. Only throwed if the keystore is not initialized
        e.printStackTrace();
        return false;
    }

    return true;
}

From source file:gov.va.med.imaging.proxy.ssl.AuthSSLProtocolSocketFactory.java

/**
 * /*from w  w w .  ja  v a  2s . c o m*/
 * @param keystoreName
 * @param keystore
 * @throws KeyStoreException
 */
private void logKeystoreContents(String keystoreName, KeyStore keystore) throws KeyStoreException {
    Logger.getLogger(AuthSSLProtocolSocketFactory.class).debug("Keystore : '" + keystoreName + "':");
    for (Enumeration<String> aliases = keystore.aliases(); aliases.hasMoreElements();) {
        String alias = (String) aliases.nextElement();
        Certificate[] certs = keystore.getCertificateChain(alias);
        if (certs != null) {
            Logger.getLogger(AuthSSLProtocolSocketFactory.class).debug("Certificate Chain '" + alias + "':");
            for (Certificate cert : certs)
                logCertificateContents(cert);
        } else {
            Certificate cert = keystore.getCertificate(alias);
            Logger.getLogger(AuthSSLProtocolSocketFactory.class)
                    .debug("Trusted Certificate Authority '" + alias + "':");
            logCertificateContents(cert);
        }
    }
}

From source file:edu.vt.middleware.crypt.KeyStoreCli.java

/**
 * Exports a certificate or key pair from the keystore.
 *
 * @param  line  Parsed command line arguments container.
 *
 * @throws  Exception  On errors.//from  w w  w.j a va 2  s  . co m
 */
protected void doExport(final CommandLine line) throws Exception {
    validateOptions(line);

    final KeyStore store = readKeyStore(line);
    final String alias = line.getOptionValue(OPT_ALIAS);
    boolean wroteData = false;
    if (line.hasOption(OPT_CERT)) {
        final File certFile = new File(line.getOptionValue(OPT_CERT));
        final Certificate[] certs = store.getCertificateChain(alias);
        if (certs != null) {
            if (certFile.getName().endsWith(PEM_SUFFIX)) {
                CryptWriter.writePemCertificates(certs, certFile);
            } else {
                CryptWriter.writeEncodedCertificates(certs, certFile);
            }
        } else {
            // Null cert chain indicates trusted cert entry
            // with single cert
            final Certificate cert = store.getCertificate(alias);
            if (certFile.getName().endsWith(PEM_SUFFIX)) {
                CryptWriter.writePemCertificate(cert, certFile);
            } else {
                CryptWriter.writeEncodedCertificate(cert, certFile);
            }
        }
        System.err.println("Wrote certificate to " + certFile);
        wroteData = true;
    }
    if (line.hasOption(OPT_KEY)) {
        final File keyFile = new File(line.getOptionValue(OPT_KEY));
        final PrivateKey key = (PrivateKey) store.getKey(alias, line.getOptionValue(OPT_PASS).toCharArray());
        if (keyFile.getName().endsWith(PEM_SUFFIX)) {
            CryptWriter.writePemKey(key, null, null, keyFile);
        } else {
            CryptWriter.writeEncodedKey(key, keyFile);
        }
        System.err.println("Wrote key to " + keyFile);
        wroteData = true;
    }
    if (!wroteData) {
        System.err.println("No data was written because neither -cert nor -key was specified.");
    }
}

From source file:be.agiv.security.demo.Main.java

private void ipStsIssueToken() {
    GridBagLayout gridBagLayout = new GridBagLayout();
    GridBagConstraints gridBagConstraints = new GridBagConstraints();
    JPanel contentPanel = new JPanel(gridBagLayout);

    JLabel urlLabel = new JLabel("URL:");
    gridBagConstraints.gridx = 0;/*from www  . ja  v a  2  s  .c  o m*/
    gridBagConstraints.gridy = 0;
    gridBagConstraints.anchor = GridBagConstraints.WEST;
    gridBagConstraints.ipadx = 5;
    gridBagLayout.setConstraints(urlLabel, gridBagConstraints);
    contentPanel.add(urlLabel);

    JTextField urlTextField = new JTextField(
            "https://auth.beta.agiv.be/ipsts/Services/DaliSecurityTokenServiceConfiguration.svc/IWSTrust13",
            60);
    gridBagConstraints.gridx++;
    gridBagLayout.setConstraints(urlTextField, gridBagConstraints);
    contentPanel.add(urlTextField);

    JLabel realmLabel = new JLabel("Realm:");
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy++;
    gridBagLayout.setConstraints(realmLabel, gridBagConstraints);
    contentPanel.add(realmLabel);

    JTextField realmTextField = new JTextField(AGIVSecurity.BETA_REALM, 30);
    gridBagConstraints.gridx++;
    gridBagLayout.setConstraints(realmTextField, gridBagConstraints);
    contentPanel.add(realmTextField);

    CredentialPanel credentialPanel = new CredentialPanel();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy++;
    gridBagConstraints.gridwidth = GridBagConstraints.REMAINDER;
    gridBagLayout.setConstraints(credentialPanel, gridBagConstraints);
    contentPanel.add(credentialPanel);

    int result = JOptionPane.showConfirmDialog(this, contentPanel, "IP-STS Issue Token",
            JOptionPane.OK_CANCEL_OPTION);
    if (result == JOptionPane.CANCEL_OPTION) {
        return;
    }

    String location = urlTextField.getText();
    String username = credentialPanel.getUsername();
    String password = credentialPanel.getPassword();
    File pkcs12File = credentialPanel.getPKCS12File();
    String realm = realmTextField.getText();

    IPSTSClient ipStsClient = new IPSTSClient(location, realm);
    try {
        if (null != username) {
            this.ipStsSecurityToken = ipStsClient.getSecurityToken(username, password);
        } else {
            KeyStore keyStore = KeyStore.getInstance("PKCS12");
            keyStore.load(new FileInputStream(pkcs12File), password.toCharArray());
            String alias = keyStore.aliases().nextElement();
            X509Certificate certificate = (X509Certificate) keyStore.getCertificate(alias);
            PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, password.toCharArray());
            this.ipStsSecurityToken = ipStsClient.getSecuritytoken(certificate, privateKey);
        }
        this.ipStsViewMenuItem.setEnabled(true);
        this.rStsIssueMenuItem.setEnabled(true);
        ipStsViewToken();
    } catch (Exception e) {
        showException(e);
    }
}