Example usage for javax.security.cert X509Certificate getPublicKey

List of usage examples for javax.security.cert X509Certificate getPublicKey

Introduction

In this page you can find the example usage for javax.security.cert X509Certificate getPublicKey.

Prototype

public abstract PublicKey getPublicKey();

Source Link

Document

Gets the public key from this certificate.

Usage

From source file:mx.com.quadrum.service.util.firma.ValidacionesCertificado.java

/**
 * Mtodo que valida el password y que la llave privada corresponda a la
 * llave publica//from w w w .j  a  v  a2  s  .c  o m
 *
 * @return true si el password y llave privada corresponden, en otro caso
 * false
 */
public boolean validaCorrespondencias() {

    try {

        PKCS8Key pkcs8 = new PKCS8Key(this.clavePrivada, this.password.toCharArray());
        //valida el pass
        PrivateKey pk = pkcs8.getPrivateKey();
        //valida que la llave privada corresponda  a la llave publica
        X509Certificate cert = X509Certificate.getInstance(this.clavePublica);
        Signature firma = Signature.getInstance("SHA1withRSA");
        firma.initSign(pk);
        byte[] firmado = firma.sign();
        firma.initVerify(cert.getPublicKey());
        if (firma.verify(firmado)) {
            return this.correcto;
        } else {
            return this.error;
        }
    } catch (GeneralSecurityException e) {

        return this.error;
    } catch (CertificateException e) {

        return this.error;
    }
}

From source file:com.tremolosecurity.idp.providers.Saml2Idp.java

private void procAuthnReq(HttpServletRequest request, HttpServletResponse response,
        DocumentBuilderFactory factory, String saml, String relayState) throws ParserConfigurationException,
        SAXException, IOException, UnmarshallingException, Exception, UnsupportedEncodingException,
        NoSuchAlgorithmException, InvalidKeyException, SignatureException, ServletException {
    AuthnRequestUnmarshaller marshaller = new AuthnRequestUnmarshaller();
    DocumentBuilder builder = factory.newDocumentBuilder();

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

    AuthnRequest authn = (AuthnRequest) marshaller.unmarshall(root);

    String issuer = authn.getIssuer().getValue();

    String authnCtx = null;/*from   w  w  w.j a  v  a2s . c o m*/

    if (authn.getRequestedAuthnContext() == null
            || authn.getRequestedAuthnContext().getAuthnContextClassRefs().size() == 0
            || authn.getRequestedAuthnContext().getAuthnContextClassRefs().get(0)
                    .getAuthnContextClassRef() == null) {
        //no authnCtx information, use default
        authnCtx = null;
    } else {
        authnCtx = authn.getRequestedAuthnContext().getAuthnContextClassRefs().get(0).getAuthnContextClassRef();
    }

    String nameID = null;

    if (authn.getNameIDPolicy() == null) {
        nameID = null;
    } else {
        nameID = authn.getNameIDPolicy().getFormat();
    }

    String binding = authn.getProtocolBinding();
    String url = authn.getAssertionConsumerServiceURL();

    if (logger.isDebugEnabled()) {
        logger.debug("Issuer : '" + issuer + "'");
        logger.debug("Binding : '" + binding + "'");
        logger.debug("URL : '" + url + "'");

        logger.debug("NameID Format : '" + nameID + "'");
        logger.debug("Authn Class Ctx : '" + authnCtx + "'");
    }

    Saml2Trust trust = this.trusts.get(issuer);

    if (trust == null) {
        StringBuffer b = new StringBuffer();
        b.append("Could not find a trust for issuer '").append(issuer).append("'");
        throw new Exception(b.toString());
    }

    String authnSig = request.getParameter("Signature");
    if (authnSig != null) {
        String sigAlg = request.getParameter("SigAlg");
        StringBuffer query = new StringBuffer();
        query.append("SAMLRequest=").append(URLEncoder.encode(request.getParameter("SAMLRequest"), "UTF-8"));
        if (relayState != null) {
            query.append("&RelayState=").append(URLEncoder.encode(relayState, "UTF-8"));
        }
        query.append("&SigAlg=").append(URLEncoder.encode(sigAlg, "UTF-8"));

        String validationCert = trust.spSigCert;
        UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG);
        java.security.cert.X509Certificate cert = holder.getConfig().getCertificate(validationCert);

        if (!Saml2Idp.xmlDigSigAlgs.containsKey(sigAlg)) {
            throw new Exception("Invalid signature algorithm : " + sigAlg);
        }

        if (!authn.getDestination().equals(request.getRequestURL().toString())) {
            throw new Exception("Invalid destination");
        }

        Signature sigv = Signature.getInstance(Saml2Idp.javaDigSigAlgs.get(sigAlg));

        sigv.initVerify(cert.getPublicKey());
        sigv.update(query.toString().getBytes("UTF-8"));

        if (!sigv.verify(Base64.decodeBase64(authnSig.getBytes("UTF-8")))) {
            throw new Exception("Signature verification failed");
        }

    } else if (this.requireSignedAuthn) {
        throw new Exception("No signature on the authentication request");
    }

    doFederation(request, response, issuer, nameID, authnCtx, url, relayState, trust);
}

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

private String procLogoutResp(HttpServletRequest request, HttpServletResponse response,
        DocumentBuilderFactory factory, String saml, String relayState, String url)
        throws ParserConfigurationException, SAXException, IOException, UnmarshallingException, Exception,
        UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException, SignatureException,
        ServletException {//from w w  w .  ja va  2s.  c  o m

    LogoutResponseUnmarshaller marshaller = new LogoutResponseUnmarshaller();
    DocumentBuilder builder = factory.newDocumentBuilder();

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

    LogoutResponse logout = (LogoutResponse) marshaller.unmarshall(root);

    String issuer = logout.getIssuer().getValue();

    boolean found = false;

    String algType = null;
    String logoutURL = null;
    String sigKeyName = null;

    //Search for the right mechanism configuration
    for (String chainname : cfgMgr.getAuthChains().keySet()) {
        AuthChainType act = cfgMgr.getAuthChains().get(chainname);
        for (AuthMechType amt : act.getAuthMech()) {
            for (ParamType pt : amt.getParams().getParam()) {
                if (pt.getName().equalsIgnoreCase("entityID") && pt.getValue().equalsIgnoreCase(issuer)) {
                    //found the correct mechanism
                    found = true;

                    for (ParamType ptx : amt.getParams().getParam()) {
                        if (ptx.getName().equalsIgnoreCase("sigAlg")) {
                            algType = ptx.getValue();
                        } else if (ptx.getName().equalsIgnoreCase("logoutURL")) {
                            logoutURL = ptx.getValue();
                        } else if (ptx.getName().equalsIgnoreCase("idpSigKeyName")) {
                            sigKeyName = ptx.getValue();
                        }
                    }

                    break;

                }
            }

            if (found) {
                break;
            }
        }

        if (found) {
            break;
        }
    }

    if (!found) {
        throw new ServletException("Entity ID '" + issuer + "' not found");
    }

    String authnSig = request.getParameter("Signature");
    if (authnSig != null) {
        String sigAlg = request.getParameter("SigAlg");
        StringBuffer query = new StringBuffer();

        String qs = request.getQueryString();
        query.append(OpenSAMLUtils.getRawQueryStringParameter(qs, "SAMLResponse"));
        query.append('&');
        query.append(OpenSAMLUtils.getRawQueryStringParameter(qs, "RelayState"));
        query.append('&');
        query.append(OpenSAMLUtils.getRawQueryStringParameter(qs, "SigAlg"));

        java.security.cert.X509Certificate cert = this.cfgMgr.getCertificate(sigKeyName);

        String xmlAlg = SAML2Auth.xmlDigSigAlgs.get(algType);

        if (!sigAlg.equalsIgnoreCase(xmlAlg)) {
            throw new Exception("Invalid signature algorithm : '" + sigAlg + "'");
        }

        /*if (! logout.getDestination().equals(request.getRequestURL().toString())) {
           throw new Exception("Invalid destination");
        }*/

        java.security.Signature sigv = java.security.Signature
                .getInstance(SAML2Auth.javaDigSigAlgs.get(algType));

        sigv.initVerify(cert.getPublicKey());
        sigv.update(query.toString().getBytes("UTF-8"));

        if (!sigv.verify(Base64.decodeBase64(authnSig.getBytes("UTF-8")))) {
            throw new Exception("Signature verification failed");
        }

    }

    response.sendRedirect(logoutURL);

    return logoutURL;
}

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

private String procLogoutReq(HttpServletRequest request, HttpServletResponse response,
        DocumentBuilderFactory factory, String saml, String relayState, String url)
        throws ParserConfigurationException, SAXException, IOException, UnmarshallingException, Exception,
        UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException, SignatureException,
        ServletException {//  w  ww. j  ava2  s. c o  m

    LogoutRequestUnmarshaller marshaller = new LogoutRequestUnmarshaller();
    DocumentBuilder builder = factory.newDocumentBuilder();

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

    org.opensaml.saml.saml2.core.impl.LogoutRequestImpl logout = (org.opensaml.saml.saml2.core.impl.LogoutRequestImpl) marshaller
            .unmarshall(root);

    String issuer = logout.getIssuer().getValue();

    boolean found = false;

    String algType = null;
    String logoutURL = null;
    String sigKeyName = null;

    //Search for the right mechanism configuration
    for (String chainname : cfgMgr.getAuthChains().keySet()) {
        AuthChainType act = cfgMgr.getAuthChains().get(chainname);
        for (AuthMechType amt : act.getAuthMech()) {
            for (ParamType pt : amt.getParams().getParam()) {
                if (pt.getName().equalsIgnoreCase("entityID") && pt.getValue().equalsIgnoreCase(issuer)) {
                    //found the correct mechanism
                    found = true;

                    for (ParamType ptx : amt.getParams().getParam()) {
                        if (ptx.getName().equalsIgnoreCase("sigAlg")) {
                            algType = ptx.getValue();
                        } else if (ptx.getName().equalsIgnoreCase("triggerLogoutURL")) {
                            logoutURL = ptx.getValue();
                        } else if (ptx.getName().equalsIgnoreCase("idpSigKeyName")) {
                            sigKeyName = ptx.getValue();
                        }
                    }

                    break;

                }
            }

            if (found) {
                break;
            }
        }

        if (found) {
            break;
        }
    }

    if (!found) {
        throw new ServletException("Entity ID '" + issuer + "' not found");
    }

    String authnSig = request.getParameter("Signature");
    if (authnSig != null) {
        String sigAlg = request.getParameter("SigAlg");
        StringBuffer query = new StringBuffer();

        String qs = request.getQueryString();
        query.append(OpenSAMLUtils.getRawQueryStringParameter(qs, "SAMLRequest"));
        query.append('&');
        if (request.getParameter("RelayState") != null) {
            query.append(OpenSAMLUtils.getRawQueryStringParameter(qs, "RelayState"));
            query.append('&');
        }

        query.append(OpenSAMLUtils.getRawQueryStringParameter(qs, "SigAlg"));

        java.security.cert.X509Certificate cert = this.cfgMgr.getCertificate(sigKeyName);

        String xmlAlg = SAML2Auth.xmlDigSigAlgs.get(algType);

        if (!sigAlg.equalsIgnoreCase(xmlAlg)) {
            throw new Exception("Invalid signature algorithm : '" + sigAlg + "'");
        }

        /*if (! logout.getDestination().equals(request.getRequestURL().toString())) {
           throw new Exception("Invalid destination");
        }*/

        java.security.Signature sigv = java.security.Signature
                .getInstance(SAML2Auth.javaDigSigAlgs.get(algType));

        sigv.initVerify(cert.getPublicKey());
        sigv.update(query.toString().getBytes("UTF-8"));

        if (!sigv.verify(Base64.decodeBase64(authnSig.getBytes("UTF-8")))) {
            throw new Exception("Signature verification failed");
        }

    }

    response.sendRedirect(logoutURL);

    return logoutURL;
}

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");
        }//  w  ww .  j a  v a2s . c om

        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);
}