Java Code Examples for org.opensaml.xml.util.Base64#decode()

The following examples show how to use org.opensaml.xml.util.Base64#decode() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SAML2SSOManager.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
public void processResponse(HttpServletRequest request, HttpServletResponse response)
        throws SSOAgentException {

    String saml2SSOResponse = request.getParameter(SSOAgentConstants.SAML2SSO.HTTP_POST_PARAM_SAML2_RESP);

    if (saml2SSOResponse != null) {
        String decodedResponse = new String(Base64.decode(saml2SSOResponse), Charset.forName("UTF-8"));
        XMLObject samlObject = SSOAgentUtils.unmarshall(decodedResponse);
        if (samlObject instanceof LogoutResponse) {
            //This is a SAML response for a single logout request from the SP
            doSLO(request);
        } else {
            processSSOResponse(request);
        }
        String relayState = request.getParameter(RelayState.DEFAULT_ELEMENT_LOCAL_NAME);

        if (relayState != null && !relayState.isEmpty() && !"null".equalsIgnoreCase(relayState)) { //additional
            // checks for incompetent IdPs
            ssoAgentConfig.getSAML2().setRelayState(relayState);
        }

    } else {
        throw new SSOAgentException("Invalid SAML2 Response. SAML2 Response can not be null.");
    }
}
 
Example 2
Source File: HTTPRedirectDeflateDecoder.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Base64 decodes the SAML message and then decompresses the message.
 * 
 * @param message Base64 encoded, DEFALTE compressed, SAML message
 * 
 * @return the SAML message
 * 
 * @throws MessageDecodingException thrown if the message can not be decoded
 */
protected InputStream decodeMessage(String message) throws MessageDecodingException {
    log.debug("Base64 decoding and inflating SAML message");

    byte[] decodedBytes = Base64.decode(message);
    if(decodedBytes == null){
        log.error("Unable to Base64 decode incoming message");
        throw new MessageDecodingException("Unable to Base64 decode incoming message");
    }
    
    try {
        ByteArrayInputStream bytesIn = new ByteArrayInputStream(decodedBytes);
        InflaterInputStream inflater = new InflaterInputStream(bytesIn, new Inflater(true));
        return inflater;
    } catch (Exception e) {
        log.error("Unable to Base64 decode and inflate SAML message", e);
        throw new MessageDecodingException("Unable to Base64 decode and inflate SAML message", e);
    }
}
 
Example 3
Source File: InlineX509DataProvider.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Find the certificate from the chain that matches one of the specified digests.
 * 
 * @param certs list of certificates to evaluate
 * @param digests X509 digests to use as search criteria
 * @return the matching certificate, or null
 */
protected X509Certificate findCertFromDigest(List<X509Certificate> certs, List<XMLObject> digests) {
    byte[] certValue;
    byte[] xmlValue;
    
    for (XMLObject xo : digests) {
        if (!(xo instanceof X509Digest)) {
            continue;
        }
        X509Digest digest = (X509Digest) xo;
        if (!DatatypeHelper.isEmpty(digest.getValue())) {
            xmlValue = Base64.decode(digest.getValue());
            for (X509Certificate cert : certs) {
                try {
                    certValue = X509Util.getX509Digest(cert, digest.getAlgorithm());
                    if (certValue != null && Arrays.equals(xmlValue, certValue)) {
                        return cert;
                    }
                } catch (SecurityException e) {
                    // Ignore as no match.
                }
            }
        }
    }
    return null;
}
 
Example 4
Source File: HTTPPostSimpleSignEncoder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Build the form control data string over which the signature is computed.
 * 
 * @param velocityContext the Velocity context which is already populated with the values for SAML message and relay
 *            state
 * @param messageContext  the SAML message context being processed
 * @param sigAlgURI the signature algorithm URI
 * 
 * @return the form control data string for signature computation
 */
protected String buildFormDataToSign(VelocityContext velocityContext, SAMLMessageContext messageContext, String sigAlgURI) {
    StringBuilder builder = new StringBuilder();

    boolean isRequest = false;
    if (velocityContext.get("SAMLRequest") != null) {
        isRequest = true;
    }

    String msgB64;
    if (isRequest) {
        msgB64 = (String) velocityContext.get("SAMLRequest");
    } else {
        msgB64 = (String) velocityContext.get("SAMLResponse");
    }

    String msg = null;
    try {
        msg = new String(Base64.decode(msgB64), "UTF-8");
    } catch (UnsupportedEncodingException e) {
        // All JVM's required to support UTF-8
    }

    if (isRequest) {
        builder.append("SAMLRequest=" + msg);
    } else {
        builder.append("SAMLResponse=" + msg);
    }

    if (messageContext.getRelayState() != null) {
        builder.append("&RelayState=" + messageContext.getRelayState());
    }

    builder.append("&SigAlg=" + sigAlgURI);

    return builder.toString();
}
 
Example 5
Source File: SignatureUtil.java    From jam-collaboration-sample with Apache License 2.0 5 votes vote down vote up
public static X509Certificate makeCertificate(String certificateBase64) {
    if (certificateBase64 == null || certificateBase64.isEmpty()) {
        throw new IllegalArgumentException("Supplied 'certificateBase64' argument is null or empty.");
    }

    try {
        byte[] certRaw = Base64.decode(certificateBase64);           
        CertificateFactory certFactory = CertificateFactory.getInstance(PUBLIC_CERT_ALGORITHM);
        return (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(certRaw));
    } catch (Exception e) {
        throw new RuntimeException("Unable to deserialize supplied X509 certificate.", e);
    }
}
 
Example 6
Source File: SignatureUtil.java    From jam-collaboration-sample with Apache License 2.0 5 votes vote down vote up
public static X509Certificate makeCertificate(String certificateBase64) {
    if (certificateBase64 == null || certificateBase64.isEmpty()) {
        throw new IllegalArgumentException("Supplied 'certificateBase64' argument is null or empty.");
    }

    try {
        byte[] certRaw = Base64.decode(certificateBase64);           
        CertificateFactory certFactory = CertificateFactory.getInstance(PUBLIC_CERT_ALGORITHM);
        return (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(certRaw));
    } catch (Exception e) {
        throw new RuntimeException("Unable to deserialize supplied X509 certificate.", e);
    }
}
 
Example 7
Source File: SignatureUtil.java    From jam-collaboration-sample with Apache License 2.0 5 votes vote down vote up
public static X509Certificate makeCertificate(String certificateBase64) {
    if (certificateBase64 == null || certificateBase64.isEmpty()) {
        throw new IllegalArgumentException("Supplied 'certificateBase64' argument is null or empty.");
    }

    try {
        byte[] certRaw = Base64.decode(certificateBase64);           
        CertificateFactory certFactory = CertificateFactory.getInstance(PUBLIC_CERT_ALGORITHM);
        return (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(certRaw));
    } catch (Exception e) {
        throw new RuntimeException("Unable to deserialize supplied X509 certificate.", e);
    }
}
 
Example 8
Source File: DefaultSAML2SSOManager.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
@Override
public void processResponse(HttpServletRequest request) throws SAMLSSOException {

    doBootstrap();
    String decodedResponse = new String(Base64.decode(request.getParameter(
            SSOConstants.HTTP_POST_PARAM_SAML2_RESP)));
    XMLObject samlObject = unmarshall(decodedResponse);
    if (samlObject instanceof LogoutResponse) {
        //This is a SAML response for a single logout request from the SP
        doSLO(request);
    } else {
        processSSOResponse(request);
    }
}
 
Example 9
Source File: HTTPPostDecoder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
protected void doDecode(MessageContext messageContext) throws MessageDecodingException {
    if (!(messageContext instanceof SAMLMessageContext)) {
        log.error("Invalid message context type, this decoder only support SAMLMessageContext");
        throw new MessageDecodingException(
                "Invalid message context type, this decoder only support SAMLMessageContext");
    }

    if (!(messageContext.getInboundMessageTransport() instanceof HTTPInTransport)) {
        log.error("Invalid inbound message transport type, this decoder only support HTTPInTransport");
        throw new MessageDecodingException(
                "Invalid inbound message transport type, this decoder only support HTTPInTransport");
    }

    SAMLMessageContext samlMsgCtx = (SAMLMessageContext) messageContext;

    HTTPInTransport inTransport = (HTTPInTransport) samlMsgCtx.getInboundMessageTransport();
    if (!inTransport.getHTTPMethod().equalsIgnoreCase("POST")) {
        throw new MessageDecodingException("This message decoder only supports the HTTP POST method");
    }

    String relayState = inTransport.getParameterValue("TARGET");
    samlMsgCtx.setRelayState(relayState);
    log.debug("Decoded SAML relay state (TARGET parameter) of: {}", relayState);

    String base64Message = inTransport.getParameterValue("SAMLResponse");
    byte[] decodedBytes = Base64.decode(base64Message);
    if (decodedBytes == null) {
        log.error("Unable to Base64 decode SAML message");
        throw new MessageDecodingException("Unable to Base64 decode SAML message");
    }

    SAMLObject inboundMessage = (SAMLObject) unmarshallMessage(new ByteArrayInputStream(decodedBytes));
    samlMsgCtx.setInboundMessage(inboundMessage);
    samlMsgCtx.setInboundSAMLMessage(inboundMessage);
    log.debug("Decoded SAML message");

    populateMessageContext(samlMsgCtx);
}
 
Example 10
Source File: InlineX509DataProvider.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Find the certificate from the chain that contains one of the specified subject key identifiers.
 * 
 * @param certs list of certificates to evaluate
 * @param skis X509 subject key identifiers to use as search criteria
 * @return the matching certificate, or null
 */
protected X509Certificate findCertFromSubjectKeyIdentifier(List<X509Certificate> certs, List<X509SKI> skis) {
    for (X509SKI ski : skis) {
        if (! DatatypeHelper.isEmpty(ski.getValue())) {
            byte[] xmlValue = Base64.decode(ski.getValue());
            for (X509Certificate cert : certs) {
                byte[] certValue = X509Util.getSubjectKeyIdentifier(cert);
                if (certValue != null && Arrays.equals(xmlValue, certValue)) {
                    return cert;
                }
            }
        }
    }
    return null;
}
 
Example 11
Source File: SAML2SSOManager.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
protected void processSSOResponse(HttpServletRequest request) throws SSOAgentException {

        LoggedInSessionBean sessionBean = new LoggedInSessionBean();
        sessionBean.setSAML2SSO(sessionBean.new SAML2SSO());

        String saml2ResponseString =
                new String(Base64.decode(request.getParameter(
                        SSOAgentConstants.SAML2SSO.HTTP_POST_PARAM_SAML2_RESP)), Charset.forName("UTF-8"));
        Response saml2Response = (Response) SSOAgentUtils.unmarshall(saml2ResponseString);
        sessionBean.getSAML2SSO().setResponseString(saml2ResponseString);
        sessionBean.getSAML2SSO().setSAMLResponse(saml2Response);

        Assertion assertion = null;
        if (ssoAgentConfig.getSAML2().isAssertionEncrypted()) {
            List<EncryptedAssertion> encryptedAssertions = saml2Response.getEncryptedAssertions();
            EncryptedAssertion encryptedAssertion = null;
            if (!CollectionUtils.isEmpty(encryptedAssertions)) {
                encryptedAssertion = encryptedAssertions.get(0);
                try {
                    assertion = getDecryptedAssertion(encryptedAssertion);
                } catch (Exception e) {
                    if (log.isDebugEnabled()) {
                        log.debug("Assertion decryption failure : ", e);
                    }
                    throw new SSOAgentException("Unable to decrypt the SAML2 Assertion");
                }
            }
        } else {
            List<Assertion> assertions = saml2Response.getAssertions();
            if (assertions != null && !assertions.isEmpty()) {
                assertion = assertions.get(0);
            }
        }
        if (assertion == null) {
            if (isNoPassive(saml2Response)) {
                LOGGER.log(Level.FINE, "Cannot authenticate in passive mode");
                return;
            }
            throw new SSOAgentException("SAML2 Assertion not found in the Response");
        }

        String idPEntityIdValue = assertion.getIssuer().getValue();
        if (idPEntityIdValue == null || idPEntityIdValue.isEmpty()) {
            throw new SSOAgentException("SAML2 Response does not contain an Issuer value");
        } else if (!idPEntityIdValue.equals(ssoAgentConfig.getSAML2().getIdPEntityId())) {
            throw new SSOAgentException("SAML2 Response Issuer verification failed");
        }
        sessionBean.getSAML2SSO().setAssertion(assertion);
        // Cannot marshall SAML assertion here, before signature validation due to a weird issue in OpenSAML

        // Get the subject name from the Response Object and forward it to login_action.jsp
        String subject = null;
        if (assertion.getSubject() != null && assertion.getSubject().getNameID() != null) {
            subject = assertion.getSubject().getNameID().getValue();
        }

        if (subject == null) {
            throw new SSOAgentException("SAML2 Response does not contain the name of the subject");
        }


        sessionBean.getSAML2SSO().setSubjectId(subject); // set the subject
        request.getSession().setAttribute(SSOAgentConstants.SESSION_BEAN_NAME, sessionBean);

        // validate audience restriction
        validateAudienceRestriction(assertion);

        // validate signature
        validateSignature(saml2Response, assertion);

        // Marshalling SAML2 assertion after signature validation due to a weird issue in OpenSAML
        sessionBean.getSAML2SSO().setAssertionString(marshall(assertion));

        ((LoggedInSessionBean) request.getSession().getAttribute(
                SSOAgentConstants.SESSION_BEAN_NAME)).getSAML2SSO().
                setSubjectAttributes(getAssertionStatements(assertion));

        //For removing the session when the single sign out request made by the SP itself
        if (ssoAgentConfig.getSAML2().isSLOEnabled()) {
            String sessionId = assertion.getAuthnStatements().get(0).getSessionIndex();
            if (sessionId == null) {
                throw new SSOAgentException("Single Logout is enabled but IdP Session ID not found in SAML2 Assertion");
            }
            ((LoggedInSessionBean) request.getSession().getAttribute(
                    SSOAgentConstants.SESSION_BEAN_NAME)).getSAML2SSO().setSessionIndex(sessionId);
            SSOAgentSessionManager.addAuthenticatedSession(request.getSession(false));
        }

        request.getSession().setAttribute(SSOAgentConstants.SESSION_BEAN_NAME, sessionBean);

    }
 
Example 12
Source File: SignatureUtil.java    From jam-collaboration-sample with Apache License 2.0 4 votes vote down vote up
/**
 * convert basee64 signature to a raw signature
 */
private static byte[] getRawSignatureFromBase64(final String signature) {      
    return Base64.decode(signature);       
}
 
Example 13
Source File: SignatureUtil.java    From jam-collaboration-sample with Apache License 2.0 4 votes vote down vote up
/**
 * convert basee64 signature to a raw signature
 */
private static byte[] getRawSignatureFromBase64(final String signature) {      
    return Base64.decode(signature);       
}
 
Example 14
Source File: BaseSAMLSimpleSignatureSecurityPolicyRule.java    From lams with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Extract the signature value from the request, in the form suitable for input into
 * {@link SignatureTrustEngine#validate(byte[], byte[], String, CriteriaSet, Credential)}.
 * 
 * Defaults to the Base64-decoded value of the HTTP request parameter named <code>Signature</code>.
 * 
 * @param request the HTTP servlet request
 * @return the signature value
 * @throws SecurityPolicyException thrown if there is an error during request processing
 */
protected byte[] getSignature(HttpServletRequest request) throws SecurityPolicyException {
    String signature = request.getParameter("Signature");
    if (DatatypeHelper.isEmpty(signature)) {
        return null;
    }
    return Base64.decode(signature);
}
 
Example 15
Source File: SecurityHelper.java    From lams with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Build Java CRL from base64 encoding.
 * 
 * @param base64CRL base64-encoded CRL
 * @return a native Java X509 CRL
 * @throws CertificateException thrown if there is an error constructing certificate
 * @throws CRLException  thrown if there is an error constructing CRL
 */
public static java.security.cert.X509CRL buildJavaX509CRL(String base64CRL)
        throws CertificateException, CRLException {
    CertificateFactory  cf = CertificateFactory.getInstance("X.509");
    ByteArrayInputStream input = new ByteArrayInputStream(Base64.decode(base64CRL));
    return (java.security.cert.X509CRL) cf.generateCRL(input);
}
 
Example 16
Source File: Util.java    From carbon-commons with Apache License 2.0 2 votes vote down vote up
/**
 * Decoding and deflating the encoded AuthReq
 *
 * @param encodedStr encoded AuthReq
 * @return decoded AuthReq
 */
public static String decode(String encodedStr) throws Exception {
   return new String(Base64.decode(encodedStr));
}
 
Example 17
Source File: KeyInfoHelper.java    From lams with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Decode a base64-encoded ds:CryptoBinary value to a native Java BigInteger type.
 *
 * @param base64Value base64-encoded CryptoBinary value
 * @return the decoded BigInteger
 */
public static final BigInteger decodeBigIntegerFromCryptoBinary(String base64Value) {
   return new BigInteger(1, Base64.decode(base64Value));
}
 
Example 18
Source File: SecurityHelper.java    From lams with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Build Java EC public key from base64 encoding.
 * 
 * @param base64EncodedKey base64-encoded EC public key
 * @return a native Java ECPublicKey
 * @throws KeyException thrown if there is an error constructing key
 */
public static ECPublicKey buildJavaECPublicKey(String base64EncodedKey) throws KeyException {
    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.decode(base64EncodedKey));
    return (ECPublicKey) buildKey(keySpec, "EC");
}
 
Example 19
Source File: SecurityHelper.java    From lams with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Build Java RSA public key from base64 encoding.
 * 
 * @param base64EncodedKey base64-encoded RSA public key
 * @return a native Java RSAPublicKey
 * @throws KeyException thrown if there is an error constructing key
 */
public static RSAPublicKey buildJavaRSAPublicKey(String base64EncodedKey) throws KeyException {
    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.decode(base64EncodedKey));
    return (RSAPublicKey) buildKey(keySpec, "RSA");
}
 
Example 20
Source File: SecurityHelper.java    From lams with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Build Java DSA public key from base64 encoding.
 * 
 * @param base64EncodedKey base64-encoded DSA public key
 * @return a native Java DSAPublicKey
 * @throws KeyException thrown if there is an error constructing key
 */
public static DSAPublicKey buildJavaDSAPublicKey(String base64EncodedKey) throws KeyException {
    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.decode(base64EncodedKey));
    return (DSAPublicKey) buildKey(keySpec, "DSA");
}