org.opensaml.xml.util.Base64 Java Examples

The following examples show how to use org.opensaml.xml.util.Base64. 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: SAMLSSOUtil.java    From carbon-identity with Apache License 2.0 7 votes vote down vote up
public static String decodeForPost(String encodedStr)
        throws IdentityException {
    try {
        org.apache.commons.codec.binary.Base64 base64Decoder = new org.apache.commons.codec.binary.Base64();
        byte[] xmlBytes = encodedStr.getBytes("UTF-8");
        byte[] base64DecodedByteArray = base64Decoder.decode(xmlBytes);

        String decodedString = new String(base64DecodedByteArray, "UTF-8");
        if (log.isDebugEnabled()) {
            log.debug("Request message " + decodedString);
        }
        return decodedString;

    } catch (IOException e) {
        throw IdentityException.error(
                "Error when decoding the SAML Request.", e);
    }

}
 
Example #2
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 #3
Source File: HTTPPostDecoder.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Gets the Base64 encoded message from the request and decodes it.
 * 
 * @param transport inbound message transport
 * 
 * @return decoded message
 * 
 * @throws MessageDecodingException thrown if the message does not contain a base64 encoded SAML message
 */
protected InputStream getBase64DecodedMessage(HTTPInTransport transport) throws MessageDecodingException {
    log.debug("Getting Base64 encoded message from request");
    String encodedMessage = transport.getParameterValue("SAMLRequest");
    if (DatatypeHelper.isEmpty(encodedMessage)) {
        encodedMessage = transport.getParameterValue("SAMLResponse");
    }

    if (DatatypeHelper.isEmpty(encodedMessage)) {
        log.error("Request did not contain either a SAMLRequest or "
                + "SAMLResponse paramter.  Invalid request for SAML 2 HTTP POST binding.");
        throw new MessageDecodingException("No SAML message present in request");
    }

    log.trace("Base64 decoding SAML message:\n{}", encodedMessage);
    byte[] decodedBytes = Base64.decode(encodedMessage);
    if(decodedBytes == null){
        log.error("Unable to Base64 decode SAML message");
        throw new MessageDecodingException("Unable to Base64 decode SAML message");
    }

    log.trace("Decoded SAML message:\n{}", new String(decodedBytes));
    return new ByteArrayInputStream(decodedBytes);
}
 
Example #4
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 #5
Source File: HTTPRedirectDeflateEncoder.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * DEFLATE (RFC1951) compresses the given SAML message.
 * 
 * @param message SAML message
 * 
 * @return DEFLATE compressed message
 * 
 * @throws MessageEncodingException thrown if there is a problem compressing the message
 */
protected String deflateAndBase64Encode(SAMLObject message) throws MessageEncodingException {
    log.debug("Deflating and Base64 encoding SAML message");
    try {
        String messageStr = XMLHelper.nodeToString(marshallMessage(message));

        ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
        Deflater deflater = new Deflater(Deflater.DEFLATED, true);
        DeflaterOutputStream deflaterStream = new DeflaterOutputStream(bytesOut, deflater);
        deflaterStream.write(messageStr.getBytes("UTF-8"));
        deflaterStream.finish();

        return Base64.encodeBytes(bytesOut.toByteArray(), Base64.DONT_BREAK_LINES);
    } catch (IOException e) {
        throw new MessageEncodingException("Unable to DEFLATE and Base64 encode SAML message", e);
    }
}
 
Example #6
Source File: HTTPPostEncoder.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Populate the Velocity context instance which will be used to render the POST body.
 * 
 * @param velocityContext the Velocity context instance to populate with data
 * @param messageContext the SAML message context source of data
 * @param endpointURL endpoint URL to which to encode message
 * @throws MessageEncodingException thrown if there is a problem encoding the message
 */
protected void populateVelocityContext(VelocityContext velocityContext, SAMLMessageContext messageContext,
        String endpointURL) throws MessageEncodingException {
    
    Encoder esapiEncoder = ESAPI.encoder();

    String encodedEndpointURL = esapiEncoder.encodeForHTMLAttribute(endpointURL);
    log.debug("Encoding action url of '{}' with encoded value '{}'", endpointURL, encodedEndpointURL);
    velocityContext.put("action", encodedEndpointURL);
    velocityContext.put("binding", getBindingURI());

    log.debug("Marshalling and Base64 encoding SAML message");
    if (messageContext.getOutboundSAMLMessage().getDOM() == null) {
        marshallMessage(messageContext.getOutboundSAMLMessage());
    }
    try {
        String messageXML = XMLHelper.nodeToString(messageContext.getOutboundSAMLMessage().getDOM());
        String encodedMessage = Base64.encodeBytes(messageXML.getBytes("UTF-8"), Base64.DONT_BREAK_LINES);
        if (messageContext.getOutboundSAMLMessage() instanceof RequestAbstractType) {
            velocityContext.put("SAMLRequest", encodedMessage);
        } else if (messageContext.getOutboundSAMLMessage() instanceof StatusResponseType) {
            velocityContext.put("SAMLResponse", encodedMessage);
        } else {
            throw new MessageEncodingException(
                    "SAML message is neither a SAML RequestAbstractType or StatusResponseType");
        }
    } catch (UnsupportedEncodingException e) {
        log.error("UTF-8 encoding is not supported, this VM is not Java compliant.");
        throw new MessageEncodingException("Unable to encode message, UTF-8 encoding is not supported");
    }

    String relayState = messageContext.getRelayState();
    if (checkRelayState(relayState)) {
        String encodedRelayState = esapiEncoder.encodeForHTMLAttribute(relayState);
        log.debug("Setting RelayState parameter to: '{}', encoded as '{}'", relayState, encodedRelayState);
        velocityContext.put("RelayState", encodedRelayState);
    }
}
 
Example #7
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 #8
Source File: SAMLUtils.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
public static String encodeSAMLRequest(XMLObject authnRequest)
        throws MarshallingException, IOException {
    Marshaller marshaller = Configuration.getMarshallerFactory()
            .getMarshaller(authnRequest);
    Element authDOM = marshaller.marshall(authnRequest);
    StringWriter requestWriter = new StringWriter();
    XMLHelper.writeNode(authDOM, requestWriter);
    String requestMessage = requestWriter.toString();
    Deflater deflater = new Deflater(Deflater.DEFLATED, true);
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteArrayOutputStream, deflater);
    deflaterOutputStream.write(requestMessage.getBytes(Charset.forName("UTF-8")));
    deflaterOutputStream.close();
    String encodedRequestMessage = Base64.encodeBytes(byteArrayOutputStream.toByteArray(), Base64.DONT_BREAK_LINES);
    encodedRequestMessage = URLEncoder.encode(encodedRequestMessage, HttpUtils.UTF_8).trim();
    return encodedRequestMessage;
}
 
Example #9
Source File: SSOAgentUtils.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
public static void addDeflateSignatureToHTTPQueryString(StringBuilder httpQueryString,
                                                        X509Credential cred) throws SSOAgentException {
    doBootstrap();
    try {
        httpQueryString.append("&SigAlg="
                + URLEncoder.encode(XMLSignature.ALGO_ID_SIGNATURE_RSA, "UTF-8").trim());

        java.security.Signature signature = java.security.Signature.getInstance("SHA1withRSA");
        signature.initSign(cred.getPrivateKey());
        signature.update(httpQueryString.toString().getBytes(Charset.forName("UTF-8")));
        byte[] signatureByteArray = signature.sign();

        String signatureBase64encodedString = Base64.encodeBytes(signatureByteArray,
                Base64.DONT_BREAK_LINES);
        httpQueryString.append("&Signature="
                + URLEncoder.encode(signatureBase64encodedString, "UTF-8").trim());
    } catch (Exception e) {
        throw new SSOAgentException("Error applying SAML2 Redirect Binding signature", e);
    }
}
 
Example #10
Source File: KeyInfoHelper.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Build an {@link X509Digest} containing the digest of the specified certificate.
 * 
 * @param javaCert the Java X509Certificate to digest
 * @param algorithmURI  digest algorithm URI
 * @return a new X509Digest object
 * @throws NoSuchAlgorithmException if the algorithm specified cannot be used
 * @throws CertificateEncodingException if the certificate cannot be encoded
 */
public static X509Digest buildX509Digest(X509Certificate javaCert, String algorithmURI)
        throws NoSuchAlgorithmException, CertificateEncodingException {
    
    String jceAlg = SecurityHelper.getAlgorithmIDFromURI(algorithmURI);
    if (jceAlg == null) {
        throw new NoSuchAlgorithmException("No JCE algorithm found for " + algorithmURI);
    }
    MessageDigest md = MessageDigest.getInstance(jceAlg);
    byte[] hash = md.digest(javaCert.getEncoded());
    
    X509Digest xmlDigest = (X509Digest) Configuration.getBuilderFactory()
        .getBuilder(X509Digest.DEFAULT_ELEMENT_NAME)
        .buildObject(X509Digest.DEFAULT_ELEMENT_NAME);
    xmlDigest.setAlgorithm(algorithmURI);
    xmlDigest.setValue(Base64.encodeBytes(hash));
    
    return xmlDigest;
}
 
Example #11
Source File: DefaultSAML2SSOManager.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * This method handles the logout requests from the IdP
 * Any request for the defined logout URL is handled here
 *
 * @param request
 * @throws javax.servlet.ServletException
 * @throws IOException
 */
public void doSLO(HttpServletRequest request) throws SAMLSSOException {

    doBootstrap();
    XMLObject samlObject = null;
    if (request.getParameter(SSOConstants.HTTP_POST_PARAM_SAML2_AUTH_REQ) != null) {
        samlObject = unmarshall(new String(Base64.decode(request.getParameter(
                SSOConstants.HTTP_POST_PARAM_SAML2_AUTH_REQ))));
    }
    if (samlObject == null) {
        samlObject = unmarshall(new String(Base64.decode(request.getParameter(
                SSOConstants.HTTP_POST_PARAM_SAML2_RESP))));
    }
    if (samlObject instanceof LogoutRequest) {
        LogoutRequest logoutRequest = (LogoutRequest) samlObject;
        String sessionIndex = logoutRequest.getSessionIndexes().get(0).getSessionIndex();
    } else if (samlObject instanceof LogoutResponse) {
        request.getSession().invalidate();
    } else {
        throw new SAMLSSOException("Invalid Single Logout SAML Request");
    }
}
 
Example #12
Source File: SSOUtils.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
public static String decodeForPost(String encodedStr)
        throws SAMLSSOException {
    try {
        org.apache.commons.codec.binary.Base64 base64Decoder = new org.apache.commons.codec.binary.Base64();
        byte[] xmlBytes = encodedStr.getBytes("UTF-8");
        byte[] base64DecodedByteArray = base64Decoder.decode(xmlBytes);

        String decodedString = new String(base64DecodedByteArray, "UTF-8");
        if (log.isDebugEnabled()) {
            log.debug("Request message " + decodedString);
        }
        return decodedString;

    } catch (IOException e) {
        throw new SAMLSSOException(
                "Error when decoding the SAML Request.", e);
    }
}
 
Example #13
Source File: SSOAgentUtils.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
private static Signature setSignatureRaw(String signatureAlgorithm, X509Credential cred) throws SSOAgentException {
    Signature signature = (Signature) buildXMLObject(Signature.DEFAULT_ELEMENT_NAME);
    signature.setSigningCredential(cred);
    signature.setSignatureAlgorithm(signatureAlgorithm);
    signature.setCanonicalizationAlgorithm(Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);

    try {
        KeyInfo keyInfo = (KeyInfo) buildXMLObject(KeyInfo.DEFAULT_ELEMENT_NAME);
        X509Data data = (X509Data) buildXMLObject(X509Data.DEFAULT_ELEMENT_NAME);
        org.opensaml.xml.signature.X509Certificate cert =
                (org.opensaml.xml.signature.X509Certificate) buildXMLObject(org.opensaml.xml.signature.X509Certificate.DEFAULT_ELEMENT_NAME);
        String value =
                org.apache.xml.security.utils.Base64.encode(cred.getEntityCertificate().getEncoded());
        cert.setValue(value);
        data.getX509Certificates().add(cert);
        keyInfo.getX509Datas().add(data);
        signature.setKeyInfo(keyInfo);
        return signature;

    } catch (CertificateEncodingException e) {
        throw new SSOAgentException("Error getting certificate", e);
    }
}
 
Example #14
Source File: SAML2HTTPRedirectDeflateSignatureValidator.java    From carbon-identity with Apache License 2.0 6 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)}
 * .
 * <p/>
 * Defaults to the Base64-decoded value of the HTTP request parameter named
 * <code>Signature</code>.
 *
 * @param queryString
 * @return
 * @throws SecurityPolicyException
 * @throws IdentitySAML2SSOException
 */
protected static byte[] getSignature(String queryString) throws SecurityPolicyException {
    String signatureQueryParam = HTTPTransportUtils.getRawQueryStringParameter(queryString, "Signature");
    if (DatatypeHelper.isEmpty(signatureQueryParam)) {
        throw new SecurityPolicyException("Could not extract the Signature from query string");
    }
    String signature = null;
    try {
        /* Split 'Signature=<sig_value>' query param using '=' as the delimiter,
    and get the Signature value */
        signature = URLDecoder.decode(signatureQueryParam.split("=")[1], "UTF-8");
    } catch (UnsupportedEncodingException e) {
        if (log.isDebugEnabled()) {
            log.debug("Encoding not supported.", e);
        }
        // JVM is required to support UTF-8
        return new byte[0];
    }
    return Base64.decode(signature);
}
 
Example #15
Source File: OAuth2SAMLWorkflowSample.java    From jam-collaboration-sample with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an OAuth2 access token from a SAML bearer assertion
 * POST /api/v1/auth/token
 */
private static String postOAuth2AccessToken(
        String baseUrl,
        String clientKey,
        String clientSecret,
        String idpId,
        String subjectNameId,
        String subjectNameIdFormat,
        String subjectNameIdQualifier,
        PrivateKey idpPrivateKey) throws Exception {
    
    System.out.println("\n***************************************************************");
    String urlString = baseUrl + "/api/v1/auth/token";
    System.out.println("POST " + urlString);
  
    URL requestUrl = new URL(urlString);
    
    Assertion assertion = buildSAML2Assertion(baseUrl, subjectNameId, subjectNameIdFormat, subjectNameIdQualifier, idpId, clientKey, clientSecret == null);
    String signedAssertion = signAssertion(assertion, idpPrivateKey);
    System.out.println("Signed assertion: " + signedAssertion);
    
    List<Pair<String,String>> postParams = new ArrayList<Pair<String,String>>();
    postParams.add(new Pair<String,String>("client_id", URLEncoder.encode(clientKey, "UTF-8")));
    if (clientSecret != null) {
        postParams.add(new Pair<String,String>("client_secret", URLEncoder.encode(clientSecret, "UTF-8")));
    }
    postParams.add(new Pair<String,String>("grant_type", URLEncoder.encode(SAML2_BEARER_GRANT_TYPE, "UTF-8")));
    String base64SamlAssertion = new String(Base64.encodeBytes(signedAssertion.getBytes(), Base64.DONT_BREAK_LINES));
   
    postParams.add(new Pair<String,String>("assertion", URLEncoder.encode(base64SamlAssertion, "UTF-8")));   
   
    String requestBody = joinPostBodyParams(postParams);
    System.out.println("Request body: " + requestBody);
     
    return postOAuth2AccessTokenHelper(requestUrl,requestBody);
}
 
Example #16
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 #17
Source File: WebServicePostEncoder.java    From MaxKey with Apache License 2.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
 */
@SuppressWarnings("rawtypes")
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 #18
Source File: OAuth2SAMLWorkflowSample.java    From jam-collaboration-sample with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an OAuth2 access token from a SAML bearer assertion
 * POST /api/v1/auth/token
 */
private static String postOAuth2AccessToken(PrivateKey idpPrivateKey) throws Exception {
    
    System.out.println("\n***************************************************************");
    String urlString = BASE_URL + "/api/v1/auth/token";
    System.out.println("POST " + urlString);
  
    URL requestUrl = new URL(urlString);
    
    Assertion assertion = buildSAML2Assertion(clientSecret == null);
    String signedAssertion = signAssertion(assertion, idpPrivateKey);
    System.out.println("Signed assertion: " + signedAssertion);
    
    List<Pair<String,String>> postParams = new ArrayList<Pair<String,String>>();
    postParams.add(new Pair<String,String>("client_id", URLEncoder.encode(CLIENT_KEY, "UTF-8")));
    if (clientSecret != null) {
        postParams.add(new Pair<String,String>("client_secret", URLEncoder.encode(clientSecret, "UTF-8")));
    }
    postParams.add(new Pair<String,String>("grant_type", URLEncoder.encode(SAML2_BEARER_GRANT_TYPE, "UTF-8")));
    String base64SamlAssertion = new String(Base64.encodeBytes(signedAssertion.getBytes(), Base64.DONT_BREAK_LINES));
   
    postParams.add(new Pair<String,String>("assertion", URLEncoder.encode(base64SamlAssertion, "UTF-8")));   
   
    String requestBody = joinPostBodyParams(postParams);
    System.out.println("Request body: " + requestBody);
     
    return postOAuth2AccessTokenHelper(requestUrl,requestBody);
}
 
Example #19
Source File: SAMLSSOUtil.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Compresses the response String
 *
 * @param response
 * @return
 * @throws IOException
 */
public static String compressResponse(String response) throws IOException {

    Deflater deflater = new Deflater(Deflater.DEFLATED, true);
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteArrayOutputStream, deflater);
    try {
        deflaterOutputStream.write(response.getBytes(StandardCharsets.UTF_8));
        return Base64.encodeBytes(byteArrayOutputStream.toByteArray(), Base64.DONT_BREAK_LINES);
    } finally {
        deflaterOutputStream.close();
    }
}
 
Example #20
Source File: SAMLSSOUtil.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Encoding the response
 *
 * @param xmlString String to be encoded
 * @return encoded String
 */
public static String encode(String xmlString) {
    // Encoding the message
    String encodedRequestMessage =
            Base64.encodeBytes(xmlString.getBytes(StandardCharsets.UTF_8),
                    Base64.DONT_BREAK_LINES);
    return encodedRequestMessage.trim();
}
 
Example #21
Source File: SAML2GrantAccessTokenRequestor.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public static void getAccessToken(HttpServletRequest request) throws SSOAgentException {


        String samlAssertionString = ((SSOAgentSessionBean) request.getSession().getAttribute(
                SSOAgentConfigs.getSessionBeanName())).getSAMLSSOSessionBean().getSAMLAssertionString();

        try {

            String consumerKey = SSOAgentConfigs.getOAuth2ClientId();
            String consumerSecret = SSOAgentConfigs.getOAuth2ClientSecret();
            String tokenEndpoint = SSOAgentConfigs.getTokenEndpoint();
            String keySecret = consumerKey+":"+consumerSecret;

            String accessTokenResponse = executePost(tokenEndpoint,
                    SAML2_BEARER_ASSERTION + URLEncoder.encode(Base64
                            .encodeBytes(samlAssertionString.getBytes(Charset.forName("UTF-8"))).replaceAll("\n", "")),
                    Base64.encodeBytes(keySecret.getBytes(Charset.forName
                            ("UTF-8")))
                    .replace("\n",
                            ""));

            Gson gson = new Gson();
            SSOAgentSessionBean.AccessTokenResponseBean accessTokenResp =
                    gson.fromJson(accessTokenResponse, SSOAgentSessionBean.AccessTokenResponseBean.class);

            ((SSOAgentSessionBean) request.getSession().getAttribute(
                    SSOAgentConfigs.getSessionBeanName())).getSAMLSSOSessionBean()
                    .setAccessTokenResponseBean(accessTokenResp);

        } catch (Exception e) {
            throw new SSOAgentException("Error while retrieving OAuth2 access token using SAML2 grant type", e);
        }
    }
 
Example #22
Source File: SignatureUtil.java    From jam-collaboration-sample with Apache License 2.0 5 votes vote down vote up
/**
 * convert a base64 encoded certificate into a java object public key
 */
public static PublicKey makePublicKey(final String certificateBase64) {

    if (certificateBase64 == null || certificateBase64.isEmpty()) {
        throw new IllegalArgumentException("Supplied 'certificateBase64' argument is null or empty.");
    }

    try {
        final CertificateFactory cf = CertificateFactory.getInstance(PUBLIC_CERT_ALGORITHM);
        final Certificate certificate = cf.generateCertificate(new ByteArrayInputStream(Base64.decode(certificateBase64)));
        return certificate.getPublicKey();
    } catch (final CertificateException e) {
        throw new RuntimeException("Unable to generate certificates (" + PUBLIC_CERT_ALGORITHM + ") " + e.getMessage(), e);
    } 
}
 
Example #23
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 #24
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 #25
Source File: ClientCertAuthRule.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
public void evaluate(MessageContext messageContext) throws SecurityPolicyException {

    Credential peerCredential = messageContext.getInboundMessageTransport().getPeerCredential();

    if (peerCredential == null) {
        log.info("Inbound message transport did not contain a peer credential, "
                + "skipping client certificate authentication");
        return;
    }
    if (!(peerCredential instanceof X509Credential)) {
        log.info("Inbound message transport did not contain an X509Credential, "
                + "skipping client certificate authentication");
        return;
    }

    X509Credential requestCredential = (X509Credential) peerCredential;
    if (log.isDebugEnabled()) {
        try {
            log.debug("Attempting to authenticate inbound connection that presented the certificate:");
            log.debug(Base64.encodeBytes(requestCredential.getEntityCertificate().getEncoded()));
        } catch (CertificateEncodingException e) {
            // do nothing
        }
    }
    doEvaluate(requestCredential, messageContext);
}
 
Example #26
Source File: SignatureUtil.java    From jam-collaboration-sample with Apache License 2.0 5 votes vote down vote up
/**
 * convert a base64 encoded certificate into a java object public key
 */
public static PublicKey makePublicKey(final String certificateBase64) {

    if (certificateBase64 == null || certificateBase64.isEmpty()) {
        throw new IllegalArgumentException("Supplied 'certificateBase64' argument is null or empty.");
    }

    try {
        final CertificateFactory cf = CertificateFactory.getInstance(PUBLIC_CERT_ALGORITHM);
        final Certificate certificate = cf.generateCertificate(new ByteArrayInputStream(Base64.decode(certificateBase64)));
        return certificate.getPublicKey();
    } catch (final CertificateException e) {
        throw new RuntimeException("Unable to generate certificates (" + PUBLIC_CERT_ALGORITHM + ") " + e.getMessage(), e);
    } 
}
 
Example #27
Source File: Util.java    From carbon-identity with Apache License 2.0 5 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 SAML2SSOUIAuthenticatorException {

    try {
        org.apache.commons.codec.binary.Base64 base64Decoder = new org.apache.commons.codec.binary.Base64();
        byte[] xmlBytes = encodedStr.getBytes("UTF-8");
        byte[] base64DecodedByteArray = base64Decoder.decode(xmlBytes);

        return new String(base64DecodedByteArray, 0, base64DecodedByteArray.length, "UTF-8");

    } catch (IOException e) {
        throw new SAML2SSOUIAuthenticatorException("Error when decoding the SAML Request.", e);
    }

}
 
Example #28
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 #29
Source File: SignatureUtil.java    From jam-collaboration-sample with Apache License 2.0 5 votes vote down vote up
/**
 * convert a base64 encoded certificate into a java object public key
 */
public static PublicKey makePublicKey(final String certificateBase64) {

    if (certificateBase64 == null || certificateBase64.isEmpty()) {
        throw new IllegalArgumentException("Supplied 'certificateBase64' argument is null or empty.");
    }

    try {
        final CertificateFactory cf = CertificateFactory.getInstance(PUBLIC_CERT_ALGORITHM);
        final Certificate certificate = cf.generateCertificate(new ByteArrayInputStream(Base64.decode(certificateBase64)));
        return certificate.getPublicKey();
    } catch (final CertificateException e) {
        throw new RuntimeException("Unable to generate certificates (" + PUBLIC_CERT_ALGORITHM + ") " + e.getMessage(), e);
    } 
}
 
Example #30
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);
    }
}