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:org.apache.commons.httpclient.contrib.ssl.AuthSSLProtocolSocketFactory.java

private SSLContext createSSLContext() {
    try {//from w w w . j  a  va  2s. c  o 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 {/*from   www  .j  a v a 2  s  .com*/
        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());
    }
}

From source file:com.app.mvc.http.ext.AuthSSLProtocolSocketFactory.java

private SSLContext createSSLContext() {
    try {/*from w w  w. j a  v  a  2s.  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:org.miloss.fgsms.bueller.AuthSSLProtocolSocketFactory.java

private SSLContext createSSLContext() {
    try {//ww  w. jav 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());
    }
    return null;
}

From source file:au.edu.monash.merc.capture.util.httpclient.ssl.AuthSSLProtocolSocketFactory.java

@SuppressWarnings("rawtypes")
private SSLContext createSSLContext() {
    try {//from   w  w  w.j  a v a 2 s .  c  o  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:org.ovirt.engine.core.utils.ssl.AuthSSLProtocolSocketFactory.java

private SSLContext createSSLContext() {
    try {//from  ww  w . j  a  v  a2  s.com
        KeyManager[] keymanagers = null;
        TrustManager[] trustmanagers = null;
        if (this.keystoreUrl != null) {
            KeyStore keystore = createKeyStore(this.keystoreUrl, this.keystorePassword);
            if (LOG.isDebugEnabled()) {
                Enumeration<String> aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = 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<String> aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = 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("SSLv3");
        sslcontext.init(keymanagers, trustmanagers, null);
        return sslcontext;
    } catch (NoSuchAlgorithmException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationException("Unsupported algorithm exception: " + e.getMessage());
    } catch (KeyStoreException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationException("Keystore exception: " + e.getMessage());
    } catch (GeneralSecurityException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationException("Key management exception: " + e.getMessage());
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationException(
                "I/O error reading keystore/truststore file: " + e.getMessage());
    }
}

From source file:it.greenvulcano.gvesb.http.ssl.AuthSSLProtocolSocketFactory.java

private SSLContext createSSLContext() {
    try {//ww w  .j  av  a 2 s  . c  o m
        KeyManager[] keymanagers = null;
        TrustManager[] trustmanagers = null;
        if (this.keystoreID != null) {
            KeyStore keystore = createKeyStore(this.keystoreID);
            if (logger.isDebugEnabled()) {
                Enumeration<String> aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = aliases.nextElement();
                    Certificate[] certs = keystore.getCertificateChain(alias);
                    if (certs != null) {
                        logger.debug("Certificate chain '" + alias + "':");
                        for (int c = 0; c < certs.length; c++) {
                            if (certs[c] instanceof X509Certificate) {
                                X509Certificate cert = (X509Certificate) certs[c];
                                logger.debug(" Certificate " + (c + 1) + ":");
                                logger.debug("  Subject DN: " + cert.getSubjectDN());
                                logger.debug("  Signature Algorithm: " + cert.getSigAlgName());
                                logger.debug("  Valid from: " + cert.getNotBefore());
                                logger.debug("  Valid until: " + cert.getNotAfter());
                                logger.debug("  Issuer: " + cert.getIssuerDN());
                            }
                        }
                    }
                }
            }
            keymanagers = createKeyManagers(keystore, this.keyPassword);
        }
        if (this.truststoreID != null) {
            KeyStore keystore = createKeyStore(this.truststoreID);
            if (logger.isDebugEnabled()) {
                Enumeration<String> aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = aliases.nextElement();
                    logger.debug("Trusted certificate '" + alias + "':");
                    Certificate trustedcert = keystore.getCertificate(alias);
                    if (trustedcert != null && trustedcert instanceof X509Certificate) {
                        X509Certificate cert = (X509Certificate) trustedcert;
                        logger.debug("  Subject DN: " + cert.getSubjectDN());
                        logger.debug("  Signature Algorithm: " + cert.getSigAlgName());
                        logger.debug("  Valid from: " + cert.getNotBefore());
                        logger.debug("  Valid until: " + cert.getNotAfter());
                        logger.debug("  Issuer: " + cert.getIssuerDN());
                    }
                }
            }
            trustmanagers = createTrustManagers(keystore);
        }
        SSLContext sslctx = SSLContext.getInstance("SSL");
        sslctx.init(keymanagers, trustmanagers, null);
        return sslctx;
    } catch (NoSuchAlgorithmException e) {
        logger.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Unsupported algorithm exception: " + e.getMessage());
    } catch (KeyStoreException e) {
        logger.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Keystore exception: " + e.getMessage());
    } catch (GeneralSecurityException e) {
        logger.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Key management exception: " + e.getMessage());
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Error reading keystore/truststore file: " + e.getMessage());
    }
}

From source file:com.tremolosecurity.openunison.util.OpenUnisonUtils.java

private static void exportIdPMetadata(Options options, CommandLine cmd, TremoloType tt, KeyStore ks)
        throws Exception, KeyStoreException, CertificateEncodingException, NoSuchAlgorithmException,
        UnrecoverableKeyException, SecurityException, MarshallingException, SignatureException {

    InitializationService.initialize();//from  w  w w  .j ava 2 s  .co m

    logger.info("Finding IdP...");
    String idpName = loadOption(cmd, "idpName", options);

    ApplicationType idp = null;

    for (ApplicationType app : tt.getApplications().getApplication()) {
        if (app.getName().equalsIgnoreCase(idpName)) {
            idp = app;
        }
    }

    if (idp == null) {
        throw new Exception("IdP '" + idpName + "' not found");
    }

    logger.info("Loading the base URL");
    String baseURL = loadOption(cmd, "urlBase", options);

    String url = baseURL + idp.getUrls().getUrl().get(0).getUri();

    SecureRandom random = new SecureRandom();
    byte[] idBytes = new byte[20];
    random.nextBytes(idBytes);

    StringBuffer b = new StringBuffer();
    b.append('f').append(Hex.encodeHexString(idBytes));
    String id = b.toString();

    EntityDescriptorBuilder edb = new EntityDescriptorBuilder();
    EntityDescriptor ed = edb.buildObject();
    ed.setID(id);
    ed.setEntityID(url);

    IDPSSODescriptorBuilder idpssdb = new IDPSSODescriptorBuilder();
    IDPSSODescriptor sd = idpssdb.buildObject();//ed.getSPSSODescriptor("urn:oasis:names:tc:SAML:2.0:protocol");
    sd.addSupportedProtocol("urn:oasis:names:tc:SAML:2.0:protocol");
    ed.getRoleDescriptors().add(sd);

    HashMap<String, List<String>> params = new HashMap<String, List<String>>();
    for (ParamType pt : idp.getUrls().getUrl().get(0).getIdp().getParams()) {
        List<String> vals = params.get(pt.getName());
        if (vals == null) {
            vals = new ArrayList<String>();
            params.put(pt.getName(), vals);
        }
        vals.add(pt.getValue());
    }

    sd.setWantAuthnRequestsSigned(params.containsKey("requireSignedAuthn")
            && params.get("requireSignedAuthn").get(0).equalsIgnoreCase("true"));

    KeyDescriptorBuilder kdb = new KeyDescriptorBuilder();

    if (params.get("encKey") != null && !params.get("encKey").isEmpty()
            && (ks.getCertificate(params.get("encKey").get(0)) != null)) {
        KeyDescriptor kd = kdb.buildObject();
        kd.setUse(UsageType.ENCRYPTION);
        KeyInfoBuilder kib = new KeyInfoBuilder();
        KeyInfo ki = kib.buildObject();

        X509DataBuilder x509b = new X509DataBuilder();
        X509Data x509 = x509b.buildObject();
        X509CertificateBuilder certb = new X509CertificateBuilder();
        org.opensaml.xmlsec.signature.X509Certificate cert = certb.buildObject();
        cert.setValue(Base64.encode(ks.getCertificate(params.get("encKey").get(0)).getEncoded()));
        x509.getX509Certificates().add(cert);
        ki.getX509Datas().add(x509);
        kd.setKeyInfo(ki);
        sd.getKeyDescriptors().add(kd);

    }

    if (params.get("sigKey") != null && !params.get("sigKey").isEmpty()
            && (ks.getCertificate(params.get("sigKey").get(0)) != null)) {
        KeyDescriptor kd = kdb.buildObject();
        kd.setUse(UsageType.SIGNING);
        KeyInfoBuilder kib = new KeyInfoBuilder();
        KeyInfo ki = kib.buildObject();

        X509DataBuilder x509b = new X509DataBuilder();
        X509Data x509 = x509b.buildObject();
        X509CertificateBuilder certb = new X509CertificateBuilder();
        org.opensaml.xmlsec.signature.X509Certificate cert = certb.buildObject();
        cert.setValue(Base64.encode(ks.getCertificate(params.get("sigKey").get(0)).getEncoded()));
        x509.getX509Certificates().add(cert);
        ki.getX509Datas().add(x509);
        kd.setKeyInfo(ki);
        sd.getKeyDescriptors().add(kd);

    }

    HashSet<String> nameids = new HashSet<String>();

    for (TrustType trustType : idp.getUrls().getUrl().get(0).getIdp().getTrusts().getTrust()) {
        for (ParamType pt : trustType.getParam()) {
            if (pt.getName().equalsIgnoreCase("nameIdMap")) {
                String val = pt.getValue().substring(0, pt.getValue().indexOf('='));
                if (!nameids.contains(val)) {
                    nameids.add(val);
                }
            }
        }
    }

    NameIDFormatBuilder nifb = new NameIDFormatBuilder();

    for (String nidf : nameids) {
        NameIDFormat nif = nifb.buildObject();
        nif.setFormat(nidf);
        sd.getNameIDFormats().add(nif);
    }

    SingleSignOnServiceBuilder ssosb = new SingleSignOnServiceBuilder();
    SingleSignOnService sso = ssosb.buildObject();
    sso.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST");
    sso.setLocation(url + "/httpPost");
    sd.getSingleSignOnServices().add(sso);

    sso = ssosb.buildObject();
    sso.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect");
    sso.setLocation(url + "/httpRedirect");
    sd.getSingleSignOnServices().add(sso);

    String signingKey = loadOptional(cmd, "signMetadataWithKey", options);

    if (signingKey != null && ks.getCertificate(signingKey) != null) {
        BasicX509Credential signingCredential = new BasicX509Credential(
                (X509Certificate) ks.getCertificate(signingKey),
                (PrivateKey) ks.getKey(signingKey, tt.getKeyStorePassword().toCharArray()));

        Signature signature = OpenSAMLUtils.buildSAMLObject(Signature.class);

        signature.setSigningCredential(signingCredential);
        signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1);
        signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);

        ed.setSignature(signature);
        try {
            XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(ed).marshall(ed);
        } catch (MarshallingException e) {
            throw new RuntimeException(e);
        }
        Signer.signObject(signature);
    }

    // Get the Subject marshaller
    EntityDescriptorMarshaller marshaller = new EntityDescriptorMarshaller();

    // Marshall the Subject
    Element assertionElement = marshaller.marshall(ed);

    logger.info(net.shibboleth.utilities.java.support.xml.SerializeSupport.nodeToString(assertionElement));
}

From source file:com.t2tierp.controller.nfe.CancelaNfe.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public Map cancelaNfe(String alias, KeyStore ks, char[] senha, String codigoUf, String ambiente,
        String chaveAcesso, String numeroProtocolo, String justificativa, String cnpj) throws Exception {
    String versaoDados = "1.00";
    String url = "";
    if (codigoUf.equals("53")) {
        if (ambiente.equals("1")) {
            url = "https://nfe.sefazvirtual.rs.gov.br/ws/recepcaoevento/recepcaoevento.asmx";
        } else if (ambiente.equals("2")) {
            url = "https://homologacao.nfe.sefazvirtual.rs.gov.br/ws/recepcaoevento/recepcaoevento.asmx";
        }//from   w w  w. j  a v a2s  . com
    }
    /* fica a cargo de cada participante definir a url que ser utiizada de acordo com o cdigo da UF
     * URLs disponveis em:
     * Homologao: http://hom.nfe.fazenda.gov.br/PORTAL/WebServices.aspx
     * Produo: http://www.nfe.fazenda.gov.br/portal/WebServices.aspx
     */

    if (url.equals("")) {
        throw new Exception("URL da sefaz no definida para o cdigo de UF = " + codigoUf);
    }

    SimpleDateFormat formatoIso = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
    String dataHoraEvento = formatoIso.format(new Date());

    String xmlCanc = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"
            + "<envEvento xmlns=\"http://www.portalfiscal.inf.br/nfe\" versao=\"" + versaoDados + "\">"
            + "<idLote>1</idLote>" + "<evento versao=\"" + versaoDados + "\">" + "<infEvento Id=\"ID" + "110111"
            + chaveAcesso + "01\">" + "<cOrgao>" + codigoUf + "</cOrgao>" + "<tpAmb>" + ambiente + "</tpAmb>"
            + "<CNPJ>" + cnpj + "</CNPJ>" + "<chNFe>" + chaveAcesso + "</chNFe>" + "<dhEvento>" + dataHoraEvento
            + "</dhEvento>" + "<tpEvento>110111</tpEvento>" + "<nSeqEvento>1</nSeqEvento>" + "<verEvento>"
            + versaoDados + "</verEvento>" + "<detEvento versao=\"" + versaoDados + "\">"
            + "<descEvento>Cancelamento</descEvento>" + "<nProt>" + numeroProtocolo + "</nProt>" + "<xJust>"
            + justificativa + "</xJust>" + "</detEvento>" + "</infEvento>" + "</evento>" + "</envEvento>";

    xmlCanc = Biblioteca.assinaXML(xmlCanc, alias, ks, senha, "#ID110111" + chaveAcesso + "01", "evento",
            "infEvento", "Id");

    X509Certificate certificate = (X509Certificate) ks.getCertificate(alias);
    PrivateKey privatekey = (PrivateKey) ks.getKey(alias, senha);
    SocketFactoryDinamico socketFactory = new SocketFactoryDinamico(certificate, privatekey);
    //arquivo que contm a cadeia de certificados do servio a ser consumido
    socketFactory.setFileCacerts(this.getClass().getResourceAsStream("/br/inf/portalfiscal/nfe/jssecacerts"));

    //define o protocolo a ser utilizado na conexo
    Protocol protocol = new Protocol("https", socketFactory, 443);
    Protocol.registerProtocol("https", protocol);

    OMElement omElement = AXIOMUtil.stringToOM(xmlCanc);

    RecepcaoEventoStub.NfeDadosMsg dadosMsg = new RecepcaoEventoStub.NfeDadosMsg();
    dadosMsg.setExtraElement(omElement);

    RecepcaoEventoStub.NfeCabecMsg cabecMsg = new RecepcaoEventoStub.NfeCabecMsg();
    cabecMsg.setCUF(codigoUf);
    cabecMsg.setVersaoDados(versaoDados);

    RecepcaoEventoStub.NfeCabecMsgE cabecMsgE = new RecepcaoEventoStub.NfeCabecMsgE();
    cabecMsgE.setNfeCabecMsg(cabecMsg);

    RecepcaoEventoStub stub = new RecepcaoEventoStub(url);

    RecepcaoEventoStub.NfeRecepcaoEventoResult result = stub.nfeRecepcaoEvento(dadosMsg, cabecMsgE);

    ByteArrayInputStream in = new ByteArrayInputStream(result.getExtraElement().toString().getBytes());

    JAXBContext jc = JAXBContext.newInstance("br.inf.portalfiscal.nfe.retevento");
    Unmarshaller unmarshaller = jc.createUnmarshaller();

    JAXBElement<br.inf.portalfiscal.nfe.retevento.TRetEnvEvento> retEvento = (JAXBElement) unmarshaller
            .unmarshal(in);

    Map map = new HashMap();
    if (retEvento.getValue().getRetEvento().get(0).getInfEvento().getCStat().equals("135")) {
        map.put("nfeCancelada", true);
        xmlCanc = xmlCancelamento(retEvento.getValue(), versaoDados, codigoUf, ambiente, chaveAcesso,
                numeroProtocolo, justificativa, cnpj, dataHoraEvento);
        xmlCanc = xmlCanc.replaceAll("xmlns:ns2=\"http://www.w3.org/2000/09/xmldsig#\"", "");

        xmlCanc = Biblioteca.assinaXML(xmlCanc, alias, ks, senha, "#ID110111" + chaveAcesso + "01", "evento",
                "infEvento", "Id");
        map.put("xmlCancelamento", xmlCanc);
    } else {
        map.put("nfeCancelada", false);
    }
    map.put("motivo1", retEvento.getValue().getXMotivo());
    map.put("motivo2", retEvento.getValue().getRetEvento().get(0).getInfEvento().getXMotivo());

    return map;
}