当前位置: 首页>>代码示例>>Java>>正文


Java Base64Support类代码示例

本文整理汇总了Java中net.shibboleth.utilities.java.support.codec.Base64Support的典型用法代码示例。如果您正苦于以下问题:Java Base64Support类的具体用法?Java Base64Support怎么用?Java Base64Support使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


Base64Support类属于net.shibboleth.utilities.java.support.codec包,在下文中一共展示了Base64Support类的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: deflateAndBase64Encode

import net.shibboleth.utilities.java.support.codec.Base64Support; //导入依赖的package包/类
/**
 * 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 = SerializeSupport.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 Base64Support.encode(bytesOut.toByteArray(), Base64Support.UNCHUNKED);
    } catch (IOException e) {
        throw new MessageEncodingException("Unable to DEFLATE and Base64 encode SAML message", e);
    }
}
 
开发者ID:yaochi,项目名称:pac4j-plus,代码行数:26,代码来源:Pac4jHTTPRedirectDeflateEncoder.java

示例2: getBase64DecodedMessage

import net.shibboleth.utilities.java.support.codec.Base64Support; //导入依赖的package包/类
protected InputStream getBase64DecodedMessage()
        throws MessageDecodingException {
    logger.debug("Getting Base64 encoded message from context, ignoring the given request");
    String encodedMessage = this.context.getRequestParameter("SAMLRequest");
    if(Strings.isNullOrEmpty(encodedMessage)) {
        encodedMessage = this.context.getRequestParameter("SAMLResponse");
    }

    if(Strings.isNullOrEmpty(encodedMessage)) {
        throw new MessageDecodingException("Request did not contain either a SAMLRequest or SAMLResponse parameter. Invalid request for SAML 2 HTTP POST binding.");
    } else {
        logger.trace("Base64 decoding SAML message:\n{}", encodedMessage);
        final byte[] decodedBytes = Base64Support.decode(encodedMessage);
        if(decodedBytes == null) {
            throw new MessageDecodingException("Unable to Base64 decode SAML message");
        } else {
            try {
                logger.trace("Decoded SAML message:\n{}", new String(decodedBytes, HttpConstants.UTF8_ENCODING));
            } catch(final UnsupportedEncodingException e) {
                throw new TechnicalException(e);
            }
            return new ByteArrayInputStream(decodedBytes);
        }
    }
}
 
开发者ID:yaochi,项目名称:pac4j-plus,代码行数:26,代码来源:Pac4jHTTPPostDecoder.java

示例3: addDeflateSignatureToHTTPQueryString

import net.shibboleth.utilities.java.support.codec.Base64Support; //导入依赖的package包/类
/**
 * Applies the XML Digital Signature to the HTTP query string specified.
 *
 * @param httpQueryString the primary HTTP query string which is to be digitally signed
 * @param credential      an entity credential associated with X.509 Public Key Infrastructure
 * @throws SSOException if an error occurs while applying the SAML 2.0 Redirect binding signature
 */
public static void addDeflateSignatureToHTTPQueryString(StringBuilder httpQueryString, X509Credential credential)
        throws SSOException {
    try {
        httpQueryString.append("&SigAlg=").
                append(URLEncoder.encode(XMLSignature.ALGO_ID_SIGNATURE_RSA, StandardCharsets.UTF_8.name()).trim());

        java.security.Signature signature = java.security.Signature.getInstance("SHA1withRSA");
        signature.initSign(credential.getPrivateKey());
        signature.update(httpQueryString.toString().getBytes(StandardCharsets.UTF_8));
        byte[] signatureByteArray = signature.sign();

        String signatureBase64EncodedString = Base64Support.encode(signatureByteArray, false);
        httpQueryString.append("&Signature=").
                append(URLEncoder.encode(signatureBase64EncodedString, StandardCharsets.UTF_8.name()).trim());
    } catch (NoSuchAlgorithmException | InvalidKeyException |
            java.security.SignatureException | UnsupportedEncodingException e) {
        throw new SSOException("Error applying SAML 2.0 Redirect Binding signature", e);
    }
}
 
开发者ID:wso2-extensions,项目名称:tomcat-extension-samlsso,代码行数:27,代码来源:SSOUtils.java

示例4: processResponse

import net.shibboleth.utilities.java.support.codec.Base64Support; //导入依赖的package包/类
/**
 * Processes a SAML 2.0 response depending on its type, either a SAML 2.0 Response for a single-sign-on (SSO)
 * SAML 2.0 Request by the client application or a SAML 2.0 Response for a single-logout (SLO) SAML 2.0 Request
 * from a service provider.
 *
 * @param request the servlet request processed
 * @throws SSOException if SAML 2.0 response is null
 */
public void processResponse(Request request) throws SSOException {
    String saml2SSOResponse = request.getParameter(Constants.HTTP_POST_PARAM_SAML_RESPONSE);

    if (saml2SSOResponse != null) {
        String decodedResponse = new String(Base64Support.decode(saml2SSOResponse), StandardCharsets.UTF_8);
        Optional<XMLObject> samlObject = SSOUtils.unmarshall(decodedResponse);
        if (samlObject.isPresent()) {
            if (samlObject.get() instanceof LogoutResponse) {
                //  this is a SAML 2.0 Response for a single logout request from the service provider
                performSingleLogout(request);
            } else {
                processSingleSignInResponse(request);
            }
        }
    } else {
        throw new SSOException("Invalid SAML 2.0 Response, SAML Response cannot be null");
    }
}
 
开发者ID:wso2-extensions,项目名称:tomcat-extension-samlsso,代码行数:27,代码来源:SAML2SSOManager.java

示例5: encode

import net.shibboleth.utilities.java.support.codec.Base64Support; //导入依赖的package包/类
@SuppressWarnings("rawtypes")
@Override
public JSONObject encode(IdPAttribute idpAttribute) throws AttributeEncodingException {
    Constraint.isNotNull(idpAttribute, "Attribute to encode cannot be null");
    String attributeString = "";
    JSONObject obj = new JSONObject();
    JSONArray array = new JSONArray();
    for (IdPAttributeValue value : idpAttribute.getValues()) {
        if (value instanceof ByteAttributeValue && value.getValue() != null) {
            if (getAsInt()) {
                // int
                JSONArray innerArray = new JSONArray();
                for (byte byteValue : ((ByteAttributeValue) value).getValue()) {
                    innerArray.add((int)byteValue);
                }
                // each byte array is converted to json int array and placed
                // to json array.
                array.add(innerArray);
            } else {
                // b64
                if (attributeString.length() > 0 && getStringDelimiter() != null) {
                    attributeString += getStringDelimiter();
                }
                attributeString += Base64Support.encode(((ByteAttributeValue) value).getValue(),
                        Base64Support.UNCHUNKED);
                if (getAsArray()) {
                    array.add(attributeString.toString());
                    attributeString = "";
                }
            }
        }
    }
    if (getAsArray() || getAsInt()) {
        obj.put(getName(), array.size() == 0 ? null : array);
    } else {
        obj.put(getName(), attributeString.toString().isEmpty() ? null : attributeString.toString());
    }
    return obj;
}
 
开发者ID:CSCfi,项目名称:shibboleth-idp-oidc-extension,代码行数:40,代码来源:OIDCByteAttributeEncoder.java

示例6: populateVelocityContext

import net.shibboleth.utilities.java.support.codec.Base64Support; //导入依赖的package包/类
/**
 * 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, MessageContext<SAMLObject> messageContext,
                                       String endpointURL) throws MessageEncodingException {

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

    SAMLObject outboundMessage = messageContext.getMessage();

    log.debug("Marshalling and Base64 encoding SAML message");
    Element domMessage = marshallMessage(outboundMessage);

    try {
        String messageXML = SerializeSupport.nodeToString(domMessage);
        String encodedMessage = Base64Support.encode(messageXML.getBytes("UTF-8"), Base64Support.UNCHUNKED);
        if (outboundMessage instanceof RequestAbstractType) {
            velocityContext.put("SAMLRequest", encodedMessage);
        } else if (outboundMessage instanceof StatusResponseType) {
            velocityContext.put("SAMLResponse", encodedMessage);
        } else {
            throw new MessageEncodingException(
                    "SAML message is neither a SAML RequestAbstractType or StatusResponseType");
        }
    } catch (UnsupportedEncodingException e) {
        throw new MessageEncodingException("Unable to encode message, UTF-8 encoding is not supported");
    }

    String relayState = SAMLBindingSupport.getRelayState(messageContext);
    if (SAMLBindingSupport.checkRelayState(relayState)) {
        String encodedRelayState = HTMLEncoder.encodeForHTMLAttribute(relayState);
        log.debug("Setting RelayState parameter to: '{}', encoded as '{}'", relayState, encodedRelayState);
        velocityContext.put("RelayState", encodedRelayState);
    }
}
 
开发者ID:yaochi,项目名称:pac4j-plus,代码行数:44,代码来源:Pac4jHTTPPostEncoder.java

示例7: testMarshallAndUnmarshall

import net.shibboleth.utilities.java.support.codec.Base64Support; //导入依赖的package包/类
/**
 * Tests marshalling and unmarshalling of {@code CurrentAddressType}.
 * 
 * @throws Exception
 *           for errors
 */
@Test
public void testMarshallAndUnmarshall() throws Exception {

  XMLObjectBuilderFactory builderFactory = XMLObjectProviderRegistrySupport.getBuilderFactory();

  Object object = builderFactory.getBuilder(CurrentAddressType.TYPE_NAME).buildObject(CurrentAddressType.TYPE_NAME.getNamespaceURI(),
    CurrentAddressType.TYPE_NAME.getLocalPart(), "eidas");
  CurrentAddressType address = CurrentAddressType.class.cast(object);

  fill(address);

  // Marshall
  Element element = OpenSAMLTestBase.marshall(address);
  Assert.assertNotNull(element);

  // Verify that we got one child element that is the Base64 encoding.
  NodeList childs = element.getChildNodes();
  Assert.assertEquals(1, childs.getLength());
  String base64 = childs.item(0).getNodeValue();
  byte[] bytes = Base64Support.decode(base64);
  Assert.assertTrue((new String(bytes)).startsWith("<eidas:"));

  // Unmarshall element
  CurrentAddressType address2 = OpenSAMLTestBase.unmarshall(element, CurrentAddressType.class);

  verify(address, address2);
  
  String swedishEidString = address2.toSwedishEidString();
  Assert.assertEquals("LocatorDesignator=6%20tr;LocatorName=10;Thoroughfare=Korta%20gatan;PostName=Solna;PostCode=19174", swedishEidString);

  // Test unmarshall again
  String xml = SerializeSupport.prettyPrintXML(element);
  Document doc = XMLObjectProviderRegistrySupport.getParserPool().parse(new ByteArrayInputStream(xml.toString().getBytes("UTF-8")));

  CurrentAddressType address3 = OpenSAMLTestBase.unmarshall(doc.getDocumentElement(), CurrentAddressType.class);
  verify(address, address3);

}
 
开发者ID:litsec,项目名称:eidas-opensaml,代码行数:45,代码来源:CurrentAddressTypeTest.java

示例8: testAttributeCreate

import net.shibboleth.utilities.java.support.codec.Base64Support; //导入依赖的package包/类
/**
 * Test that creates an attribute and places a CurrentAddessType as a value.
 * 
 * @throws Exception
 *           for errors
 */
@Test
public void testAttributeCreate() throws Exception {

  Attribute attribute = OpenSAMLTestBase.createSamlObject(Attribute.class, Attribute.DEFAULT_ELEMENT_NAME);
  attribute.getNamespaceManager().registerNamespaceDeclaration(new Namespace(EidasConstants.EIDAS_NP_NS, "eidas"));
  attribute.setName(AttributeConstants.EIDAS_CURRENT_ADDRESS_ATTRIBUTE_NAME);
  attribute.setFriendlyName(AttributeConstants.EIDAS_CURRENT_ADDRESS_ATTRIBUTE_FRIENDLY_NAME);
  attribute.setNameFormat(Attribute.URI_REFERENCE);

  XMLObjectBuilder<CurrentAddressType> builder = OpenSAMLTestBase.getBuilder(CurrentAddressType.TYPE_NAME);
  CurrentAddressType address = builder.buildObject(AttributeValue.DEFAULT_ELEMENT_NAME, 
    new QName(EidasConstants.EIDAS_NP_NS, CurrentAddressType.TYPE_NAME.getLocalPart(), "eidas"));
  fill(address);

  attribute.getAttributeValues().add(address);

  Element attrElement = OpenSAMLTestBase.marshall(attribute);

  System.out.println(SerializeSupport.prettyPrintXML(attrElement));

  // Make sure we inserted the correct namespace prefix while marshalling the CurrentAddressType
  Assert.assertTrue((new String(Base64Support.decode(attrElement.getFirstChild().getFirstChild().getNodeValue()))).startsWith("<eidas:"));

  // Unmarshall
  Attribute attribute2 = OpenSAMLTestBase.unmarshall(attrElement, Attribute.class);

  Assert.assertNotNull(attribute2);
  Assert.assertEquals(AttributeConstants.EIDAS_CURRENT_ADDRESS_ATTRIBUTE_NAME, attribute2.getName());
  Assert.assertEquals(AttributeConstants.EIDAS_CURRENT_ADDRESS_ATTRIBUTE_FRIENDLY_NAME, attribute2.getFriendlyName());

  List<XMLObject> values = attribute.getAttributeValues();
  Assert.assertTrue(values.size() == 1);
  Assert.assertTrue(values.get(0) instanceof CurrentAddressType);
  CurrentAddressType address2 = (CurrentAddressType) values.get(0);
  verify(address, address2);
}
 
开发者ID:litsec,项目名称:eidas-opensaml,代码行数:43,代码来源:CurrentAddressTypeTest.java

示例9: marshallElementContent

import net.shibboleth.utilities.java.support.codec.Base64Support; //导入依赖的package包/类
/**
 * The element content of a {@code CurrentAddressType} is the Base64-encoding of the serialized value of the
 * {@code CurrentAddressStructuredType}. So ... we have to get there by iterating over our child elements.
 */
@Override
protected void marshallElementContent(XMLObject xmlObject, Element domElement) throws MarshallingException {

  // Find out if the our namespace already has been defined, and if so, get the prefix.
  //
  final String namespace = CurrentAddressType.TYPE_NAME.getNamespaceURI();
  Optional<String> _prefix = xmlObject.getNamespaceManager()
    .getNamespaces()
    .stream()
    .filter(n -> namespace.equals(n.getNamespaceURI()))
    .map(n -> n.getNamespacePrefix())
    .findFirst();
  String prefix = _prefix.isPresent() ? _prefix.get() : CurrentAddressType.TYPE_NAME.getPrefix();
  
  StringBuilder sb = new StringBuilder();

  final List<XMLObject> childXMLObjects = xmlObject.getOrderedChildren();
  if (childXMLObjects != null && childXMLObjects.size() > 0) {
    for (final XMLObject childXMLObject : childXMLObjects) {
      if (childXMLObject == null) {
        continue;
      }
      if (!(childXMLObject instanceof XSString)) {
        throw new MarshallingException("Unexpected type of child element - " + childXMLObject.getClass().getName());
      }
      XSString childString = (XSString) childXMLObject;
      if (childString.getValue() == null) {
        continue;
      }
      String localPart = childString.getElementQName().getLocalPart();
      sb.append(String.format("<%s:%s>%s</%s:%s>", prefix, localPart, childString.getValue(), prefix, localPart));
    }
  }
  if (sb.length() > 0) {
    byte[] bytes;
    try {
      bytes = sb.toString().getBytes("UTF-8");
    }
    catch (UnsupportedEncodingException e) {
      throw new MarshallingException(e);
    }
    String base64String = Base64Support.encode(bytes, true);
    ElementSupport.appendTextContent(domElement, base64String);
  }
}
 
开发者ID:litsec,项目名称:eidas-opensaml,代码行数:50,代码来源:CurrentAddressTypeMarshaller.java


注:本文中的net.shibboleth.utilities.java.support.codec.Base64Support类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。