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

The following examples show how to use org.opensaml.xml.util.Base64#encodeBytes() . 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: 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 2
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 3
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 4
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 5
Source File: Util.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Compressing and Encoding the response
 *
 * @param xmlString String to be encoded
 * @return compressed and encoded String
 */
public static String encode(String xmlString) throws Exception {

    // Encoding the compressed message
    String encodedRequestMessage = Base64.encodeBytes(xmlString.getBytes("UTF-8"), Base64.DONT_BREAK_LINES);
    return encodedRequestMessage.trim();
}
 
Example 6
Source File: SAMLUtils.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public static String generateSAMLRequestSignature(final String urlEncodedString, final PrivateKey signingKey, final String sigAlgorithmName)
        throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, UnsupportedEncodingException {
    if (signingKey == null) {
        return urlEncodedString;
    }

    String opensamlAlgoIdSignature = SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1;
    String javaSignatureAlgorithmName = "SHA1withRSA";

    if (sigAlgorithmName.equalsIgnoreCase("SHA256")) {
        opensamlAlgoIdSignature = SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA256;
        javaSignatureAlgorithmName = "SHA256withRSA";
    } else if (sigAlgorithmName.equalsIgnoreCase("SHA384")) {
        opensamlAlgoIdSignature = SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA384;
        javaSignatureAlgorithmName = "SHA384withRSA";
    } else if (sigAlgorithmName.equalsIgnoreCase("SHA512")) {
        opensamlAlgoIdSignature = SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA512;
        javaSignatureAlgorithmName = "SHA512withRSA";
    }

    String url = urlEncodedString + "&SigAlg=" + URLEncoder.encode(opensamlAlgoIdSignature, HttpUtils.UTF_8);
    Signature signature = Signature.getInstance(javaSignatureAlgorithmName);
    signature.initSign(signingKey);
    signature.update(url.getBytes(Charset.forName("UTF-8")));
    String signatureString = Base64.encodeBytes(signature.sign(), Base64.DONT_BREAK_LINES);
    if (signatureString != null) {
        return url + "&Signature=" + URLEncoder.encode(signatureString, HttpUtils.UTF_8);
    }
    return url;
}
 
Example 7
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 8
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 9
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 10
Source File: SignatureUtil.java    From jam-collaboration-sample with Apache License 2.0 4 votes vote down vote up
public static String generateBase64Signature(final PrivateKey privateKey, final byte[] signatureBase) {
    return Base64.encodeBytes(generateRawSignature(privateKey, signatureBase));
}
 
Example 11
Source File: ErrorResponseBuilder.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
public static String encode(String authReq) {
    return Base64.encodeBytes(authReq.getBytes(StandardCharsets.UTF_8));
}
 
Example 12
Source File: SignatureUtil.java    From jam-collaboration-sample with Apache License 2.0 4 votes vote down vote up
public static String generateBase64Signature(final PrivateKey privateKey, final byte[] signatureBase) {
    return Base64.encodeBytes(generateRawSignature(privateKey, signatureBase));
}
 
Example 13
Source File: SignatureUtil.java    From jam-collaboration-sample with Apache License 2.0 4 votes vote down vote up
public static String generateBase64Signature(final PrivateKey privateKey, final byte[] signatureBase) {
    return Base64.encodeBytes(generateRawSignature(privateKey, signatureBase));
}
 
Example 14
Source File: SignatureUtil.java    From jam-collaboration-sample with Apache License 2.0 2 votes vote down vote up
/**
 * Signature Generation functions all functions take the form signature =
 * f(private key, signature base)
 * 
 */
public static String generateBase64Signature( final String privateKeyBase64, final byte[] signatureBase) {
    return Base64.encodeBytes(generateRawSignature(makePrivateKey(privateKeyBase64), signatureBase));
}
 
Example 15
Source File: SSOUtils.java    From carbon-identity with Apache License 2.0 2 votes vote down vote up
/**
 * Encoding the response
 *
 * @param xmlString String to be encoded
 * @return encoded String
 */
public static String encode(String xmlString) {
    String encodedRequestMessage = Base64.encodeBytes(xmlString.getBytes(), Base64.DONT_BREAK_LINES);
    return encodedRequestMessage.trim();
}
 
Example 16
Source File: Util.java    From carbon-identity with Apache License 2.0 2 votes vote down vote up
/**
 * Encoding the response
 *
 * @param xmlString String to be encoded
 * @return encoded String
 */
public static String encode(String xmlString) throws Exception {

    String encodedRequestMessage = Base64.encodeBytes(xmlString.getBytes(), Base64.DONT_BREAK_LINES);
    return encodedRequestMessage.trim();
}
 
Example 17
Source File: KeyInfoHelper.java    From lams with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Encode a native Java BigInteger type to a base64-encoded ds:CryptoBinary value.
 *
 * @param bigInt the BigInteger value
 * @return the encoded CryptoBinary value
 */
public static final String encodeCryptoBinaryFromBigInteger(BigInteger bigInt) {
    // This code is really complicated, for now just use the Apache xmlsec lib code directly.
    byte[] bigIntBytes = org.apache.xml.security.utils.Base64.encode(bigInt, bigInt.bitLength());
    return Base64.encodeBytes(bigIntBytes);
}
 
Example 18
Source File: SignatureUtil.java    From jam-collaboration-sample with Apache License 2.0 2 votes vote down vote up
/**
 * Signature Generation functions all functions take the form signature =
 * f(private key, signature base)
 * 
 */
public static String generateBase64Signature( final String privateKeyBase64, final byte[] signatureBase) {
    return Base64.encodeBytes(generateRawSignature(makePrivateKey(privateKeyBase64), signatureBase));
}
 
Example 19
Source File: SignatureUtil.java    From jam-collaboration-sample with Apache License 2.0 2 votes vote down vote up
/**
 * Signature Generation functions all functions take the form signature =
 * f(private key, signature base)
 * 
 */
public static String generateBase64Signature( final String privateKeyBase64, final byte[] signatureBase) {
    return Base64.encodeBytes(generateRawSignature(makePrivateKey(privateKeyBase64), signatureBase));
}
 
Example 20
Source File: AbstractSAMLArtifact.java    From lams with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Gets the Base64 encoded artifact.
 * 
 * @return Base64 encoded artifact.
 */
public String base64Encode() {
    return new String(Base64.encodeBytes(getArtifactBytes()));
}