Decode authn request xml.

@param encodedRequestXmlString the encoded request xml string
@return the request
327995
public String decodeSamlAuthnRequest(final String encodedRequestXmlString) {
        if (StringUtils.isEmpty(encodedRequestXmlString)) {
            return null;
        }

        val decodedBytes = EncodingUtils.decodeBase64(encodedRequestXmlString);
        if (decodedBytes == null) {
            return null;
        }

        return inflateAuthnRequest(decodedBytes);
    }
609835
def decode(cls, auth_header: str, encoding: str='latin1') -> 'BasicAuth':
        """"""
        try:
            auth_type, encoded_credentials = auth_header.split(' ', 1)
        except ValueError:
            raise ValueError('Could not parse authorization header.')

        if auth_type.lower() != 'basic':
            raise ValueError('Unknown authorization method %s' % auth_type)

        try:
            decoded = base64.b64decode(
                encoded_credentials.encode('ascii'), validate=True
            ).decode(encoding)
        except binascii.Error:
            raise ValueError('Invalid base64 encoding.')

        try:
            # RFC 2617 HTTP Authentication
            # https://www.ietf.org/rfc/rfc2617.txt
            # the colon must be present, but the username and password may be
            # otherwise blank.
            username, password = decoded.split(':', 1)
        except ValueError:
            raise ValueError('Invalid credentials.')

        return cls(username, password, encoding=encoding)
1083416
protected String getEncoding(HttpServletRequest request) {
        final String encoding = request.getCharacterEncoding();
        if (encoding != null) {
            return encoding;
        }

        return this.defaultEncoding;
    }
974633
public static function decode($string)
    {
        $xml = simplexml_load_string($string);
        $array = array($xml->getName() => (array) $xml);
        $array = self::loopDecode($array);

        return $array;
    }
553756
public String getAuthString() {
        String credentials = this.username + ":" + this.password;
        try {

            String encoded = new Base64().encodeAsString(credentials.getBytes("ascii"));
            return "Basic " + encoded;

        } catch (final UnsupportedEncodingException e) {

            throw new InvalidRequestException("It must be possible to encode credentials as ascii", credentials, e);

        }
    }
1237274
public String encode(XML xml) throws ParserException, SAXException, IOException {

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = null;

        InputSource is = new InputSource(new StringReader(xml.toString()));

        try {
            builder = dbFactory.newDocumentBuilder();
            Document doc = builder.parse(is);
            return net.arnx.jsonic.JSON.encode(doc, true);
        } catch (SAXException e) {
            throw new ParserException(e.getMessage());
        } catch (ParserConfigurationException e) {
            throw new ParserException(e.getMessage());
        }
    }
940704
public static Api fromXML(final String xml) throws Exception {
  	Api result=null;
  	try {
  	  result=apifactory.fromXML(xml);
  	} catch (JAXBException je) {
  		LOGGER.log(Level.SEVERE,je.getMessage());
  		LOGGER.log(Level.INFO,xml);
  		throw je;
  	}
    return result;
  }
693993
public static String encodeXML( final String    str )
    {
        if ( str == null )
        {
            return null;
        }

        StringCharacterIterator    iterator = new StringCharacterIterator( str );
        StringBuilder              result   = new StringBuilder();
        char                       c;

        for( c  = iterator.current();
             c != CharacterIterator.DONE;
             c  = iterator.next() )
        {
            if ( c == '>' )
            {
                result.append( "&gt;" );
            }
            else if ( c == '<' )
            {
                result.append( "&lt;" );
            }
            else if ( c == '&' )
            {
                result.append( "&amp;" );
            }
            else if ( c == '"' )
            {
                result.append( "&quot;" );
            }
            else if ( c == '\'' )
            {
                result.append( "&#39;" );
            }
            else
            {
                result.append( c );
            }
        }

        return result.toString();
    }
452259
private static String encodeAuthPlain(String username, char[] password) {
        // PLAIN mechanism encoding - NUL + username + NUL + password
        int size = username.length() + password.length + 2;
        ByteBuffer buffer = ByteBuffer.allocate(size);
        buffer.put((byte)0);
        buffer.put(username.getBytes());
        buffer.put((byte)0);
        buffer.put(new String(password).getBytes());
        
        buffer.flip();
        
        // Nulling out the password for security. 
        Arrays.fill(password, '\0');

        int len = buffer.remaining();
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < len; i++)
        {
            builder.append((char)(buffer.get() & 0xff)); 

        }
        String s = builder.toString();
        return s;

    }
1180832
public String processHTTPAPIRequest(
			String urlString,
			JSONObject request,
			GenericUser authenticationUser,
			String requestType, 
			String[] requestParameters,
			String... requestHedaers) throws CertificateException, IOException, JSONException {
		
		log.debug("API request: " + request.toString(4));
		String jsonRequest = request.toString();
		
		HttpURLConnection ucon = null;
		
		if("POST".equals(requestType)) {
			
			URL url = new URL(urlString);		
			log.debug("API request: " + url);
			
			ucon = (HttpURLConnection) url.openConnection();

			ucon.setRequestMethod("POST");
			ucon.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
						
			setRequestHeaders(ucon, authenticationUser, requestHedaers);
				
			for(int i = 0 ; i < requestParameters.length; i = i + 2) {
				ucon.setRequestProperty(getReferenceService().namespaceString(requestParameters[i]), getReferenceService().namespaceString(requestParameters[i+1]));
			}
			
			ucon.setUseCaches (false);
			ucon.setDoInput(true);
			ucon.setDoOutput(true);

		    //Send request
			String encodedPostRequest = "json=" + URLEncoder.encode(jsonRequest, "UTF-8");
			ucon.setRequestProperty("Content-Length", Integer.toString(encodedPostRequest.getBytes().length));
		    DataOutputStream wr = new DataOutputStream (ucon.getOutputStream ());
			wr.writeBytes(encodedPostRequest);
		    wr.flush ();
		    wr.close ();
		}
		else if ("GET".equals(requestType)) {
			log.debug("API request: " + request.toString());
			
			
			StringBuilder builder = new StringBuilder();
			builder.append(urlString + "?json=" + URLEncoder.encode(request.toString(), "UTF-8").replaceAll("\"", "%22"));
			for(int i = 0 ; i < requestParameters.length; i = i + 2) {
				builder.append("&" + getReferenceService().namespaceString(requestParameters[i]) + "=" + getReferenceService().namespaceString(requestParameters[i+1]));
			}
			
			URL url = new URL(builder.toString());		
			log.debug("API request: " + url);

			ucon = (HttpURLConnection) url.openConnection();
			setRequestHeaders(ucon, authenticationUser, requestHedaers);
			
			ucon.setConnectTimeout(5000);
			ucon.setFollowRedirects(true);
			ucon.setDoOutput(true);
		}
		else {
			throw new IllegalArgumentException("Only POST and GET API requests are supported at this stage");
		}

		
		//Obtain the response
		StringBuilder responseBuilder = new StringBuilder();
		try{			
			InputStream inputStream = ucon.getInputStream();
			
			BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
			String pre = null;                       
			while ((pre = in.readLine()) != null){
				responseBuilder.append(pre);
				responseBuilder.append("\n");
			}
			in.close();
		}
		catch (IOException e) {
			//on error codes we should not fail but just capture the response code
			log.debug("Genarating the API call response caused: ", e);
		}
		String response = responseBuilder.toString();
		
		log.debug("The generated API call response: " + response);
		
		getScenarioGlobals().setAttribute(LAST_SCENARIO_HTTP_RESPONSE_CODE_KEY, ucon.getResponseCode());
		
		return response;
	}
1144113
public static String oauthDecode(String value) throws DecoderException {
    if (value == null) {
      return "";
    }

    try {
      return new String(URLCodec.decodeUrl(value.getBytes("US-ASCII")), "UTF-8");
    }
    catch (UnsupportedEncodingException e) {
      throw new RuntimeException(e);
    }
  }
1041982
private String prepareXmlForParsing(String xml) throws TheDavidBoxClientException{
		//Escape all & symbols in the response so it can parse it later
		xml = xml.replaceAll("&", "&amp;");
		
		String xmlReady;
		try {
			//It repairs the encoding to allow all utf-8 symbols
			xmlReady = new String(xml.getBytes(), CHARSET_ENCODING);
		} catch (UnsupportedEncodingException e) {
			throw new TheDavidBoxClientException(e);
		}
		return xmlReady;
	}
1309008
public static String encodeXmlAttribute(String str) {
    if (str == null) return null;
    int len = str.length();
    if (len == 0) return str;
    StringBuffer encoded = new StringBuffer();
    for (int i = 0; i < len; i++) {
      char c = str.charAt(i);
      if (c == '<') encoded.append("&lt;");
      else if (c == '\"') encoded.append("&quot;");
      else if (c == '>') encoded.append("&gt;");
      else if (c == '\'') encoded.append("&apos;");
      else if (c == '&') encoded.append("&amp;");
      else encoded.append(c);
    }
    return encoded.toString();
  }
196530
public static String encodeXMLContent(final String content) {
		StringBuffer encoded = new StringBuffer(content);
		
		replaceAll(encoded,"&","&amp;");
		replaceAll(encoded,"\"","&quot;");
		replaceAll(encoded,"'","&apos;");
		replaceAll(encoded,"<","&lt;");
		replaceAll(encoded,">","&gt;");
		
		return encoded.toString();
	}
578564
public static Response loadFromBase64XML(Sso ssoService, String base64xml) throws CertificateException, ParserConfigurationException, SAXException, IOException {
		return loadFromBase64XML(ssoService.getSamlSettings().getIdpCertificate(), base64xml);
	}
172131
protected InputStream getBase64DecodedMessage(HTTPInTransport transport) throws MessageDecodingException {
        log.debug("Getting Base64 encoded message from request");
        String encodedMessage = transport.getParameterValue("assertion");


        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 = org.apache.commons.codec.binary.Base64.decodeBase64(encodedMessage.getBytes(StandardCharsets.UTF_8));
        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);
    }
173867
private function parseRequest( $request_xml ) {
		$xml = @simplexml_load_string($request_xml);
		if (!$xml && !$xml->getNamespaces()) { 
			// FIXME: check for protocol json-rpc
			//simplexml in combination with namespaces (soap) lets $xml evaluate to false
			return  xmlrpc_encode_request( 
				null, 
				ripcord::fault( -3, 'Invalid Method Call - Ripcord Server accepts only XML-RPC, SimpleRPC or SOAP 1.1 calls'), 
				$this->outputOptions
			);
		} else {
			// prevent segmentation fault on incorrect xmlrpc request (without methodName)
			$methodCall = $xml->xpath('//methodCall'); 
			if ($methodCall) { //xml-rpc
				$methodName = $xml->xpath('//methodName');
				if (!$methodName) {
					return xmlrpc_encode_request(
						null,
						ripcord::fault( -3, 'Invalid Method Call - No methodName given'),
						$this->outputOptions
					);
				}
			}
		}
		$method = null;
		ob_start(); // xmlrpc_decode echo expat errors if the xml is not valid, can't stop it.
		$params = xmlrpc_decode_request($request_xml, $method);
		ob_end_clean(); // clean up any xml errors
		return array( 'methodName' => $method, 'params' => $params );
	}