Example usage for java.security.cert CertificateFactory generateCertificate

List of usage examples for java.security.cert CertificateFactory generateCertificate

Introduction

In this page you can find the example usage for java.security.cert CertificateFactory generateCertificate.

Prototype

public final Certificate generateCertificate(InputStream inStream) throws CertificateException 

Source Link

Document

Generates a certificate object and initializes it with the data read from the input stream inStream .

Usage

From source file:com.corebase.android.framework.http.client.AsyncHttpClient.java

/**
 * ?SSLSocketFactory?https?/*  w ww . j a v  a2 s.  c om*/
 * 
 * @return
 * @throws KeyStoreException
 * @throws NoSuchAlgorithmException
 * @throws UnrecoverableKeyException
 * @throws KeyManagementException
 */
private CustomSSLSocketFactory initCustomSSLSocketFactory()
        throws KeyStoreException, KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException {

    KeyStore keyStore = null;
    try {
        InputStream ins = context.getAssets().open("app_pay.cer"); // ?assets
        if (ins != null) {
            CertificateFactory cerFactory = CertificateFactory.getInstance("X.509");
            Certificate cer = cerFactory.generateCertificate(ins);
            keyStore = KeyStore.getInstance("PKCS12", "BC");
            keyStore.load(null, null);
            keyStore.setCertificateEntry("trust", cer);
        } else {
            keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(null, null);
        }
        CustomSSLSocketFactory customSSLSocketFactory = new CustomSSLSocketFactory(keyStore);
        customSSLSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        return customSSLSocketFactory;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:test.be.fedict.eid.applet.PcscTest.java

@Test
public void testReadNonRepudiationCertificate() throws Exception {
    PcscEidSpi pcscEidSpi = new PcscEid(new TestView(), this.messages);
    if (false == pcscEidSpi.isEidPresent()) {
        LOG.debug("insert eID card");
        pcscEidSpi.waitForEidPresent();//w  w w . j  a  v  a 2 s.  co m
    }

    File tmpFile = File.createTempFile("eid-sign-cert-", ".der");
    byte[] signCert = pcscEidSpi.readFile(PcscEid.SIGN_CERT_FILE_ID);
    FileUtils.writeByteArrayToFile(tmpFile, signCert);

    LOG.debug("ASN1 dump: " + ASN1Dump.dumpAsString(new ASN1InputStream(signCert).readObject()));

    LOG.debug("tmp file: " + tmpFile.getAbsolutePath());

    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    X509Certificate certificate = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(signCert));
    X509Principal issuerPrincipal = PrincipalUtil.getIssuerX509Principal(certificate);
    LOG.debug("BC issuer principal: " + issuerPrincipal.getName());
    LOG.debug("Sun issuer (getName): " + certificate.getIssuerX500Principal().getName());
    LOG.debug("Sun issuer (toString): " + certificate.getIssuerX500Principal());
    String issuerName = PrincipalUtil.getIssuerX509Principal(certificate).getName().replace(",", ", ");
    LOG.debug("issuer name: " + issuerName);
    LOG.debug("certificate: " + certificate);

    pcscEidSpi.close();
}

From source file:org.atricore.idbus.capabilities.sso.support.core.signature.JSR105SamlR2SignerImpl.java

protected X509Certificate getX509Certificate(RoleDescriptorType md) {

    byte[] x509CertificateBin = getBinCertificate(md);
    if (x509CertificateBin == null)
        return null;

    try {/*from w w  w  . j  a va 2 s  . c  om*/
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        X509Certificate x509Cert = (X509Certificate) cf
                .generateCertificate(new ByteArrayInputStream(x509CertificateBin));

        return x509Cert;

    } catch (CertificateException e) {
        logger.error("Cannot get X509 Certificate " + e.getMessage(), e);

    }

    return null;

}

From source file:test.be.fedict.eid.applet.PcscTest.java

@Test
public void displayCitizenCertificates() throws Exception {
    PcscEidSpi pcscEidSpi = new PcscEid(new TestView(), this.messages);
    if (false == pcscEidSpi.isEidPresent()) {
        LOG.debug("insert eID card");
        pcscEidSpi.waitForEidPresent();// w  w w .  ja va 2  s .  c  o m
    }

    byte[] authnCertData = pcscEidSpi.readFile(PcscEid.AUTHN_CERT_FILE_ID);
    byte[] signCertData = pcscEidSpi.readFile(PcscEid.SIGN_CERT_FILE_ID);
    byte[] citizenCaCertData = pcscEidSpi.readFile(PcscEid.CA_CERT_FILE_ID);
    byte[] rootCaCertData = pcscEidSpi.readFile(PcscEid.ROOT_CERT_FILE_ID);
    byte[] nationalRegitryCertData = pcscEidSpi.readFile(PcscEid.RRN_CERT_FILE_ID);

    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    X509Certificate authnCert = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(authnCertData));
    X509Certificate signCert = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(signCertData));
    X509Certificate citizenCaCert = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(citizenCaCertData));
    X509Certificate rootCaCert = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(rootCaCertData));
    X509Certificate nationalRegitryCert = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(nationalRegitryCertData));

    LOG.debug("authentication certificate: " + authnCert);
    LOG.debug("signature certificate: " + signCert);
    LOG.debug("national registry certificate: " + nationalRegitryCert);
    LOG.debug("authn cert size: " + authnCertData.length);
    LOG.debug("sign cert size: " + signCertData.length);
    LOG.debug("citizen CA certificate: " + citizenCaCert);
    LOG.debug("root CA certificate: " + rootCaCert);
    LOG.debug("authn cert serial number: " + authnCert.getSerialNumber());
    LOG.debug("authn certificate issuer: " + authnCert.getIssuerX500Principal());

    File rootCaFile = File.createTempFile("test-root-ca-", ".pem");
    FileWriter rootCaFileWriter = new FileWriter(rootCaFile);
    PEMWriter rootCaPemWriter = new PEMWriter(rootCaFileWriter);
    rootCaPemWriter.writeObject(rootCaCert);
    rootCaPemWriter.close();

    File citizenCaFile = File.createTempFile("test-citizen-ca-", ".pem");
    FileWriter citizenCaFileWriter = new FileWriter(citizenCaFile);
    PEMWriter citizenCaPemWriter = new PEMWriter(citizenCaFileWriter);
    citizenCaPemWriter.writeObject(citizenCaCert);
    citizenCaPemWriter.close();

    pcscEidSpi.close();
    LOG.debug("root ca file: " + rootCaFile.getAbsolutePath());
    LOG.debug("citizen CA file: " + citizenCaFile.getAbsolutePath());
}

From source file:de.konqi.fitapi.auth.PublicKeysManager.java

/**
 * Forces a refresh of the public certificates downloaded from {@link #getPublicCertsEncodedUrl}.
 *
 * <p>/*from   w  w w  .j a  v  a  2  s . com*/
 * This method is automatically called from {@link #getPublicKeys()} if the public keys have not
 * yet been initialized or if the expiration time is very close, so normally this doesn't need to
 * be called. Only call this method to explicitly force the public keys to be updated.
 * </p>
 */
public PublicKeysManager refresh() throws GeneralSecurityException, IOException {
    lock.lock();
    try {
        publicKeys = new ArrayList<PublicKey>();
        // HTTP request to public endpoint
        CertificateFactory factory = SecurityUtils.getX509CertificateFactory();
        HttpResponse certsResponse = transport.createRequestFactory()
                .buildGetRequest(new GenericUrl(publicCertsEncodedUrl)).execute();
        expirationTimeMilliseconds = clock.currentTimeMillis()
                + getCacheTimeInSec(certsResponse.getHeaders()) * 1000;
        // parse each public key in the JSON response
        JsonParser parser = jsonFactory.createJsonParser(certsResponse.getContent());
        JsonToken currentToken = parser.getCurrentToken();
        // token is null at start, so get next token
        if (currentToken == null) {
            currentToken = parser.nextToken();
        }
        Preconditions.checkArgument(currentToken == JsonToken.START_OBJECT);
        try {
            while (parser.nextToken() != JsonToken.END_OBJECT) {
                parser.nextToken();
                String certValue = parser.getText();
                X509Certificate x509Cert = (X509Certificate) factory
                        .generateCertificate(new ByteArrayInputStream(StringUtils.getBytesUtf8(certValue)));
                publicKeys.add(x509Cert.getPublicKey());
            }
            publicKeys = Collections.unmodifiableList(publicKeys);
        } finally {
            parser.close();
        }
        return this;
    } finally {
        lock.unlock();
    }
}

From source file:com.cws.esolutions.security.dao.certmgmt.impl.CertificateManagerImpl.java

/**
 * @see com.cws.esolutions.security.dao.certmgmt.interfaces.ICertificateManager#applyCertificateRequest(String, File, File, String)
 *///from ww w .j a v  a  2  s.c o m
public synchronized boolean applyCertificateRequest(final String commonName, final File certificateFile,
        final File keystoreFile, final String storePassword) throws CertificateManagementException {
    final String methodName = ICertificateManager.CNAME
            + "#applyCertificateRequest(final String commonName, final File certificateFile, final File keystoreFile, final String storePassword) throws CertificateManagementException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", commonName);
        DEBUGGER.debug("Value: {}", certificateFile);
        DEBUGGER.debug("Value: {}", keystoreFile);
    }

    final File rootDirectory = certConfig.getRootDirectory();
    final File certificateDirectory = FileUtils
            .getFile(certConfig.getCertificateDirectory() + "/" + commonName);
    final File storeDirectory = FileUtils.getFile(certConfig.getStoreDirectory() + "/" + commonName);

    if (DEBUG) {
        DEBUGGER.debug("rootDirectory: {}", rootDirectory);
        DEBUGGER.debug("certificateDirectory: {}", certificateDirectory);
        DEBUGGER.debug("storeDirectory: {}", storeDirectory);
        DEBUGGER.debug("certificateFile: {}", certificateFile);
        DEBUGGER.debug("keystoreFile: {}", keystoreFile);
    }

    boolean isComplete = false;
    FileInputStream certStream = null;
    FileOutputStream storeStream = null;
    FileInputStream keystoreInput = null;
    FileInputStream rootCertStream = null;
    FileInputStream intermediateCertStream = null;

    try {
        if (!(rootDirectory.exists())) {
            throw new CertificateManagementException(
                    "Root certificate directory either does not exist or cannot be written to. Cannot continue.");
        }

        if (!(rootDirectory.canWrite())) {
            throw new CertificateManagementException(
                    "Root certificate directory either does not exist or cannot be written to. Cannot continue.");
        }

        if (!(certConfig.getRootCertificateFile().exists())) {
            throw new CertificateManagementException("Root certificate file does not exist. Cannot continue.");
        }

        if (!(certConfig.getIntermediateCertificateFile().exists())) {
            throw new CertificateManagementException(
                    "Intermediate certificate file does not exist. Cannot continue.");
        }

        if (!(storeDirectory.canWrite())) {
            throw new CertificateManagementException(
                    "Keystore directory either does not exist or cannot be written to. Cannot continue.");
        }

        if (!(keystoreFile.canWrite())) {
            throw new CertificateManagementException(
                    "Unable to write to applicable keystore. Cannot continue.");
        }

        keystoreInput = FileUtils.openInputStream(keystoreFile);
        certStream = FileUtils.openInputStream(certificateFile);

        if (DEBUG) {
            DEBUGGER.debug("keystoreInput: {}", keystoreInput);
            DEBUGGER.debug("certStream: {}", certStream);
        }

        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(keystoreInput, storePassword.toCharArray());

        if (DEBUG) {
            DEBUGGER.debug("KeyStore: {}", keyStore);
        }

        Key privateKey = keyStore.getKey(commonName, storePassword.toCharArray());
        CertificateFactory certFactory = CertificateFactory.getInstance(certConfig.getCertificateType());

        if (DEBUG) {
            DEBUGGER.debug("CertificateFactory: {}", certFactory);
        }

        rootCertStream = FileUtils.openInputStream(FileUtils.getFile(certConfig.getRootCertificateFile()));
        intermediateCertStream = FileUtils
                .openInputStream(FileUtils.getFile(certConfig.getIntermediateCertificateFile()));

        if (DEBUG) {
            DEBUGGER.debug("rootCertStream: {}", rootCertStream);
            DEBUGGER.debug("intermediateCertStream: {}", intermediateCertStream);
        }

        X509Certificate[] responseCert = new X509Certificate[] {
                (X509Certificate) certFactory.generateCertificate(rootCertStream),
                (X509Certificate) certFactory.generateCertificate(intermediateCertStream),
                (X509Certificate) certFactory.generateCertificate(certStream) };

        if (DEBUG) {
            DEBUGGER.debug("X509Certificate[]", (Object) responseCert);
        }

        storeStream = FileUtils.openOutputStream(keystoreFile);
        keyStore.setKeyEntry(commonName, privateKey, storePassword.toCharArray(), responseCert);
        keyStore.store(storeStream, storePassword.toCharArray());

        isComplete = true;
    } catch (FileNotFoundException fnfx) {
        throw new CertificateManagementException(fnfx.getMessage(), fnfx);
    } catch (IOException iox) {
        throw new CertificateManagementException(iox.getMessage(), iox);
    } catch (NoSuchAlgorithmException nsax) {
        throw new CertificateManagementException(nsax.getMessage(), nsax);
    } catch (IllegalStateException isx) {
        throw new CertificateManagementException(isx.getMessage(), isx);
    } catch (KeyStoreException ksx) {
        throw new CertificateManagementException(ksx.getMessage(), ksx);
    } catch (CertificateException cx) {
        throw new CertificateManagementException(cx.getMessage(), cx);
    } catch (UnrecoverableKeyException ukx) {
        throw new CertificateManagementException(ukx.getMessage(), ukx);
    } finally {
        if (storeStream != null) {
            IOUtils.closeQuietly(storeStream);
        }

        if (intermediateCertStream != null) {
            IOUtils.closeQuietly(intermediateCertStream);
        }

        if (rootCertStream != null) {
            IOUtils.closeQuietly(rootCertStream);
        }

        if (certStream != null) {
            IOUtils.closeQuietly(certStream);
        }

        if (keystoreInput != null) {
            IOUtils.closeQuietly(keystoreInput);
        }
    }

    return isComplete;
}

From source file:com.adito.ldap.LdapUserDatabase.java

/**
 * Return the certificat store in LDAP server for a user (if exist)
 * @param user/*from w  w  w  . ja v a 2  s  .  c  om*/
 * @return X509Certificate of the user or null id this certificate doesn't exist
 */
public X509Certificate getCertificate(User user) {

    if (logger.isInfoEnabled()) {
        logger.info("Get Certificat for " + user.getPrincipalName());
    }

    LdapTemplate ldapTemplate = new LdapTemplate();
    ldapTemplate.setContextSource(ldapContextSource);

    AndFilter filterS = new AndFilter();
    String dn = ((LdapUser) user).getDn();
    int ind = dn.indexOf(baseDn);
    String rdn = dn.substring(0, ind - 1);
    filterS.and(new EqualsFilter(OBJECT_CLASS_ATTRIBUTE, USERS_CLASS));
    filterS.and(new LikeFilter(UID_ATTRIBUTE, user.getPrincipalName()));
    List certificats = ldapTemplate.search(rdn, filterS.encode(), new AttributesMapper() {
        public Object mapFromAttributes(Attributes attrs) throws NamingException {

            try {
                CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");

                return certificateFactory.generateCertificate(
                        new ByteArrayInputStream((byte[]) attrs.get(CERTIFICATE_ATTRIBUTE).get()));

            } catch (Exception e) {

                throw new NamingException(e.toString());
            }

        }
    });

    if (certificats.size() == 0) {
        return null;
    } else {
        X509Certificate cert = (X509Certificate) certificats.get(0);
        return cert;
    }

}

From source file:ee.signwise.sdk.service.SignWiseConnection.java

/**
 * Reads certificate from stream (FileInputStream or other stream)
 * @param isCert certificate input stream
 * @return parsed certificate/* w w w.java  2  s .co m*/
 * @throws CertificateException
 * @throws IOException
 */
public X509Certificate readCertFromStream(InputStream isCert) throws CertificateException {
    X509Certificate cert = null;
    try {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        cert = (X509Certificate) certificateFactory.generateCertificate(isCert);
    } catch (CertificateException ex) {
        throw ex;
    }
    return cert;
}

From source file:com.adito.ldap.LdapUserDatabase.java

/**
 * Return the user associated to a certiciate in LDAP server
 * @param x509Certificate//  w  ww . ja  v  a  2s.c o m
 * @return the user of the certificate or null if no associate exist
 */
public User getUserByCertificate(X509Certificate x509Certificate) {

    if (logger.isInfoEnabled()) {
        logger.info("Get user for serial number " + x509Certificate.getSerialNumber().toString(16));
    }

    LdapTemplate ldapTemplate = new LdapTemplate();
    ldapTemplate.setContextSource(ldapContextSource);

    AndFilter filterS = new AndFilter();
    filterS.and(new EqualsFilter(OBJECT_CLASS_ATTRIBUTE, USERS_CLASS));
    filterS.and(new LikeFilter("userCertificate", "*"));
    for (String rdn : rdnUsers) {
        List serialNumbers = ldapTemplate.search(rdn, filterS.encode(), new AbstractContextMapper() {
            public Object doMapFromContext(DirContextOperations ctx) {

                try {
                    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");

                    X509Certificate x509Certificate = (X509Certificate) certificateFactory.generateCertificate(
                            new ByteArrayInputStream((byte[]) ctx.getObjectAttribute(CERTIFICATE_ATTRIBUTE)));

                    if (ctx.getStringAttribute(MAIL_ATTRIBUTE) == null)
                        ctx.setAttributeValue(MAIL_ATTRIBUTE, "");
                    if (ctx.getStringAttribute(COMMON_NAME_ATTRIBUTE) == null)
                        ctx.setAttributeValue(COMMON_NAME_ATTRIBUTE, "");

                    String uid = ctx.getStringAttribute(UID_ATTRIBUTE);

                    //get the date of last modify of this user
                    LdapTemplate tmp = new LdapTemplate();
                    tmp.setContextSource(ldapContextSource);
                    final String[] attrOp = { MODIFY_TIMESTAMP_ATTRIBUTE };
                    Object o = tmp.lookup(ctx.getDn(), attrOp, new ContextMapper() {
                        public Object mapFromContext(Object ctx) {
                            DirContextAdapter adapter = (DirContextAdapter) ctx;
                            return adapter.getStringAttribute(attrOp[0]);

                        }
                    }

                    );

                    Date lastPasswordChange; //the time of last change for the entry
                    if (o != null) {
                        String modifyTimestamp = o.toString();
                        lastPasswordChange = getDate(modifyTimestamp);
                    } else {
                        //if the modifyTimeStamp is null
                        lastPasswordChange = new Date();
                    }

                    LdapUser user = new LdapUser(uid, ctx.getNameInNamespace(),
                            ctx.getStringAttribute(MAIL_ATTRIBUTE),
                            ctx.getStringAttribute(COMMON_NAME_ATTRIBUTE), lastPasswordChange, getRealm());

                    Object[] tab = { x509Certificate.getSerialNumber(), user };

                    return tab;

                } catch (Exception e) {

                    logger.error(e);
                    return null;
                }
            }
        });

        if (serialNumbers != null) {
            for (Object o : serialNumbers) {

                Object[] tab = (Object[]) o;
                BigInteger serialNumber = (BigInteger) tab[0];
                LdapUser user = (LdapUser) tab[1];
                if (serialNumber.equals(x509Certificate.getSerialNumber()))
                    return user;
            }
        }
    }

    return null;

}

From source file:com.tremolosecurity.proxy.auth.SAML2Auth.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp, AuthStep as)
        throws ServletException, IOException {

    MyVDConnection myvd = cfgMgr.getMyVD();
    // HttpSession session = (HttpSession)
    // req.getAttribute(ConfigFilter.AUTOIDM_SESSION);//((HttpServletRequest)
    // req).getSession();
    // //SharedSession.getSharedSession().getSession(req.getSession().getId());
    HttpSession session = ((HttpServletRequest) req).getSession(); // SharedSession.getSharedSession().getSession(req.getSession().getId());
    UrlHolder holder = (UrlHolder) req.getAttribute(ProxyConstants.AUTOIDM_CFG);
    String urlChain = holder.getUrl().getAuthChain();
    AuthChainType act = holder.getConfig().getAuthChains().get(urlChain);

    AuthInfo userData = ((AuthController) req.getSession().getAttribute(ProxyConstants.AUTH_CTL)).getAuthInfo();

    if (userData.isAuthComplete() && userData.getAuthLevel() > 0) {
        //Session is already set, just redirect to relay state
        String relayState = this.getFinalURL(req, resp);
        if (relayState == null) {
            throw new ServletException("No RelayState or default RelayState");
        }//from w ww . ja  v a2 s.  c o  m

        resp.sendRedirect(relayState);
        return;
    }

    if (as == null) {
        //this is a special case - idp initiated means there's no context
        ArrayList<AuthStep> auths = ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL))
                .getAuthSteps();
        int id = 0;
        for (AuthMechType amt : act.getAuthMech()) {
            AuthStep asx = new AuthStep();
            asx.setId(id);
            asx.setExecuted(false);
            asx.setRequired(amt.getRequired().equals("required"));
            asx.setSuccess(false);
            auths.add(asx);
            id++;
        }

        as = auths.get(0);
    }

    HashMap<String, Attribute> authParams = (HashMap<String, Attribute>) session
            .getAttribute(ProxyConstants.AUTH_MECH_PARAMS);

    String defaultOC = authParams.get("defaultOC").getValues().get(0);

    String spEncKey = null;
    if (authParams.get("spEncKey") != null) {
        spEncKey = authParams.get("spEncKey").getValues().get(0);
    }

    RequestHolder reqHolder = ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).getHolder();

    AuthMechType amt = act.getAuthMech().get(as.getId());

    String sigCertName = authParams.get("idpSigKeyName").getValues().get(0);
    java.security.cert.X509Certificate sigCert = null;

    boolean isMultiIdp = authParams.get("isMultiIdP") != null
            && authParams.get("isMultiIdP").getValues().get(0).equalsIgnoreCase("true");

    String ldapAttrib = authParams.get("ldapAttribute").getValues().get(0);
    String dnLabel = authParams.get("dnOU").getValues().get(0);

    String samlResp = req.getParameter("SAMLResponse");
    String xml = null;

    xml = new String(Base64.decodeBase64(samlResp), "UTF-8");

    boolean assertionSigned = true;
    if (authParams.get("assertionsSigned") != null) {
        assertionSigned = Boolean.parseBoolean(authParams.get("assertionsSigned").getValues().get(0));
    }

    boolean responseSigned = false;
    if (authParams.get("responsesSigned") != null) {
        responseSigned = Boolean.parseBoolean(authParams.get("responsesSigned").getValues().get(0));
    }

    boolean assertionEncrypted = false;
    if (authParams.get("assertionEncrypted") != null) {
        assertionEncrypted = Boolean.parseBoolean(authParams.get("assertionEncrypted").getValues().get(0));
    }

    if (logger.isDebugEnabled()) {
        logger.debug("=========saml2resp============");
        logger.debug(xml);
        logger.debug("=========saml2resp============");
    }

    xml = xml.replaceAll("<!--.*-->", "");

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    try {
        DocumentBuilder builder = factory.newDocumentBuilder();

        Element root = builder.parse(new InputSource(new StringReader(xml))).getDocumentElement();

        Response samlResponse = (Response) XMLObjectSupport.getUnmarshaller(root).unmarshall(root);

        if (isMultiIdp) {

            try {
                String dn = authParams.get("idpDir").getValues().get(0);

                LDAPSearchResults res = cfgMgr.getMyVD().search(dn, 2,
                        equal("issuer", samlResponse.getIssuer().getValue()).toString(),
                        new ArrayList<String>());
                if (!res.hasMore()) {
                    throw new ServletException("No IdP found");
                }

                LDAPEntry entry = res.next();
                java.security.cert.CertificateFactory cf = java.security.cert.CertificateFactory
                        .getInstance("X.509");
                sigCert = (java.security.cert.X509Certificate) cf.generateCertificate(new ByteArrayInputStream(
                        Base64.decodeBase64(entry.getAttribute("idpSig").getStringValue())));

            } catch (LDAPException e) {
                throw new ServletException("Could not load IdP data", e);
            } catch (CertificateException e) {
                throw new ServletException("Could not load IdP data", e);
            }
        } else {
            sigCert = cfgMgr.getCertificate(sigCertName);
        }

        if (responseSigned) {
            if (samlResponse.getSignature() != null) {
                BasicCredential sigCred = new BasicCredential(sigCert.getPublicKey());
                sigCred.setUsageType(UsageType.SIGNING);

                try {
                    SAMLSignatureProfileValidator profileValidator = new SAMLSignatureProfileValidator();
                    profileValidator.validate(samlResponse.getSignature());
                    SignatureValidator.validate(samlResponse.getSignature(), sigCred);
                } catch (org.opensaml.xmlsec.signature.support.SignatureException se) {
                    throw new ServletException("Error validating response signature", se);
                }

            } else {
                throw new Exception("Response not signed");
            }
        }

        Assertion assertion = null;

        if (samlResponse.getEncryptedAssertions().size() > 0) {
            try {
                EncryptedAssertion encAssertion = samlResponse.getEncryptedAssertions().get(0);
                PrivateKey privKey = this.cfgMgr.getPrivateKey(spEncKey);

                PublicKey pubKey = this.cfgMgr.getCertificate(spEncKey).getPublicKey();
                Credential credential = new BasicCredential(pubKey, privKey);
                StaticKeyInfoCredentialResolver resolver = new StaticKeyInfoCredentialResolver(credential);
                Decrypter decrypter = new Decrypter(null, resolver, new InlineEncryptedKeyResolver());
                decrypter.setRootInNewDocument(true);
                assertion = decrypter.decrypt(encAssertion);

            } catch (Exception e) {
                throw new ServletException("Error decrypting assertion", e);
            }
        } else {
            if (assertionEncrypted) {
                throw new Exception("Assertion not encrypted");
            }

            if (samlResponse.getAssertions().size() == 0) {
                throw new Exception("No assertions found");
            }

            assertion = (Assertion) samlResponse.getAssertions().get(0);
        }

        if (assertionSigned) {
            if (assertion.getSignature() != null) {

                BasicCredential sigCred = new BasicCredential(sigCert.getPublicKey());
                sigCred.setUsageType(UsageType.SIGNING);

                try {
                    SAMLSignatureProfileValidator profileValidator = new SAMLSignatureProfileValidator();
                    profileValidator.validate(assertion.getSignature());
                    SignatureValidator.validate(assertion.getSignature(), sigCred);
                } catch (org.opensaml.xmlsec.signature.support.SignatureException se) {
                    throw new ServletException("Error validating response signature", se);
                }

            } else {
                throw new Exception("No assertion signature");
            }

        }

        //If it made it here, the assertion is valid, lets check the authncontextclassref
        Attribute authnContextClassRef = authParams.get("authCtxRef");

        if (authnContextClassRef != null && authnContextClassRef.getValues().size() > 0
                && !authnContextClassRef.getValues().get(0).isEmpty()
                && !authnContextClassRef.getValues().get(0).equalsIgnoreCase("none")
                && (assertion.getAuthnStatements() == null || assertion.getAuthnStatements().size() == 0
                        || assertion.getAuthnStatements().get(0).getAuthnContext() == null
                        || assertion.getAuthnStatements().get(0).getAuthnContext()
                                .getAuthnContextClassRef() == null
                        || assertion.getAuthnStatements().get(0).getAuthnContext() == null
                        || assertion.getAuthnStatements().get(0).getAuthnContext()
                                .getAuthnContextClassRef() == null
                        || assertion.getAuthnStatements().get(0).getAuthnContext().getAuthnContextClassRef()
                                .getAuthnContextClassRef() == null
                        || !assertion.getAuthnStatements().get(0).getAuthnContext().getAuthnContextClassRef()
                                .getAuthnContextClassRef()
                                .equalsIgnoreCase(authnContextClassRef.getValues().get(0)))) {
            logger.warn("Can not validate the authentication context classref");
            as.setSuccess(false);
            holder.getConfig().getAuthManager().nextAuth(req, resp, session, false);
            return;
        }

        try {
            if (authParams.get("dontLinkToLDAP") == null
                    || authParams.get("dontLinkToLDAP").getValues().get(0).equalsIgnoreCase("false")) {
                StringBuffer filter = new StringBuffer();
                filter.append('(').append(ldapAttrib).append('=')
                        .append(assertion.getSubject().getNameID().getValue()).append(')');

                LDAPSearchResults res = myvd.search(AuthUtil.getChainRoot(cfgMgr, act), 2, filter.toString(),
                        new ArrayList<String>());

                if (res.hasMore()) {
                    createUserFromDir(session, act, ldapAttrib, assertion, res);
                } else {
                    createUnlinkedUser(session, act, ldapAttrib, dnLabel, defaultOC, assertion);
                }
            } else {
                createUnlinkedUser(session, act, ldapAttrib, dnLabel, defaultOC, assertion);
            }
        } catch (LDAPException e) {
            if (e.getResultCode() == 32) {
                createUnlinkedUser(session, act, ldapAttrib, dnLabel, defaultOC, assertion);
            } else {
                throw e;
            }
        }

        //logout management
        Attribute logoutURLAttr = authParams.get("idpRedirLogoutURL");
        if (logoutURLAttr != null && logoutURLAttr.getValues().size() > 0
                && !logoutURLAttr.getValues().get(0).isEmpty() && authParams.get("spSigKey") != null
                && authParams.get("spSigKey").getValues().size() > 0) {
            String logoutURL = logoutURLAttr.getValues().get(0);
            String sessionIndex = assertion.getAuthnStatements().get(0).getSessionIndex();
            String nameID = assertion.getSubject().getNameID().getValue();
            String nameIDFormat = assertion.getSubject().getNameID().getFormat();

            Saml2SingleLogout handler = new Saml2SingleLogout(logoutURL, sessionIndex, nameID, nameIDFormat,
                    samlResponse.getDestination(), authParams.get("spSigKey").getValues().get(0),
                    authParams.get("sigAlg").getValues().get(0));
            LogoutUtil.addLogoutHandler(req, handler);

        }

        as.setSuccess(true);
    } catch (Exception e) {
        logger.error("Error Parsing Assertion", e);
        throw new ServletException("error parsing assertion", e);
    }

    holder.getConfig().getAuthManager().nextAuth(req, resp, session, false);
}