Format a signature for the X-OpenAPI-Authorization header
@param string $date
@param string $httpMethod
@param string $url
@param string $contentType
@return string formatted signature
427127
protected function getSignature($date, $httpMethod, $url, $contentType)
    {
        $parsedUrl = parse_url($url);

   		$signature = $httpMethod . "\n\n";
   		$signature .= $contentType . "\n";
   		$signature .= $date."\n";
   		$signature .= "x-openapi-date:" . $date . "\n";
   		if(!is_null($this->sessionId)) {
   			$signature .= "x-openapi-session-id:" . $this->sessionId . "\n";
   		}
   		$signature .= $parsedUrl['path']."\n";

        if (isset($parsedUrl['query'])) {
            parse_str($parsedUrl['query'], $parsedQuery);
            ksort($parsedQuery);
            $queryParamsCount = count($parsedQuery);
            $i = 0;
            foreach ($parsedQuery as $key => $value) {
                $signature .= '&' . $key . '=' . $value;
                if (++$i < $queryParamsCount) {
                    $signature .= "\n";
                }
            }
        }

   		return $this->accessKey . ':' . base64_encode(hash_hmac('SHA256', $signature, $this->secretAccessKey, true));
   	}
670099
function oAuthRequest($url, $method, $parameters)
    {
        if (strrpos($url, 'https://') !== 0 && strrpos($url, 'http://') !== 0) {
            $url = "{$this->host}{$url}.{$this->format}";
        }
        $request = OAuthRequest::from_consumer_and_token($this->consumer, $this->token, $method, $url, $parameters);
        $request->sign_request($this->sha1_method, $this->consumer, $this->token);
        switch ($method) {
            case 'GET':
                return $this->http($request->to_url(), 'GET');
            default:
                return $this->http($request->get_normalized_http_url(), $method, $request->to_postdata());
        }
    }
1353586
public function sendApiRest($code=200, $jsonString= '', $contentType='application/json'){
        $this->setStatusCode($code);
        $this->setContentType($contentType);
        $this->setContent($jsonString);
        $this->sendContent();
    }
897993
public String makeReplayURI(String datespec, String url) {
		String replayURI = "";
		try {
			if(url.contains(hostPort)) {
				return url;
			}
			URI uri = new URI(url);
			StringBuilder sb = new StringBuilder(90);
			sb.append("http://");
			sb.append(datespec).append(".");
			sb.append(uri.getHost()).append(".");
			sb.append(hostPort);
			sb.append(uri.getPath());
			String query = uri.getQuery();
			if(query != null && query.length() > 0) {
				sb.append("?").append(query);
			}
			replayURI = sb.toString();

		} catch (URISyntaxException e) {
			e.printStackTrace();
		}
		return replayURI;
	}
353242
private function generateMACSignature($url, $parameters, $http_method)
    {
        $timestamp = time();
        $nonce = uniqid();
        $parsed_url = parse_url($url);
        if (!isset($parsed_url['port']))
        {
            $parsed_url['port'] = ($parsed_url['scheme'] == 'https') ? 443 : 80;
        }
        if ($http_method == self::HTTP_METHOD_GET) {
            if (is_array($parameters)) {
                $parsed_url['path'] .= '?' . http_build_query($parameters, null, '&');
            } elseif ($parameters) {
                $parsed_url['path'] .= '?' . $parameters;
            }
        }

        $signature = base64_encode(hash_hmac($this->access_token_algorithm,
                    $timestamp . "\n"
                    . $nonce . "\n"
                    . $http_method . "\n"
                    . $parsed_url['path'] . "\n"
                    . $parsed_url['host'] . "\n"
                    . $parsed_url['port'] . "\n\n"
                    , $this->access_token_secret, true));

        return 'id="' . $this->access_token . '", ts="' . $timestamp . '", nonce="' . $nonce . '", mac="' . $signature . '"';
    }
697931
public function get($url, $access_token = null, $parameters = [], $contentType = 'text/xml')
    {
        return $this->doApiCall($url, 'GET', $access_token, $parameters, $contentType);
    }
138193
public static function signRequest($clientSecret, $method, $url, $body, $timestamp)
	{
		$separator = "\n";
		// Build string that need to be signed [ METHOD, URL, BODY, UNIX_TIMESTAMP ]
		$string = implode($separator, [$method, $url, $body, $timestamp]);

		// Sign
		return hash_hmac('sha256', $string, $clientSecret);
	}
1313550
private function sign($method, $uri, $date, $length){
        $sign = "{$method}&{$uri}&{$date}&{$length}&{$this->config['password']}";
        return 'UpYun ' . $this->config['username'] . ':' . md5($sign);
    }
45814
public function resolveUrlAliasSchema(Content $content, ContentType $contentType = null)
    {
        if ($contentType === null) {
            $contentType = $this->contentTypeHandler->load($content->contentInfo->contentTypeId);
        }

        return $this->resolve(
            strlen($contentType->urlAliasSchema) === 0 ? $contentType->nameSchema : $contentType->urlAliasSchema,
            $contentType,
            $content->fields,
            $content->versionInfo->languageCodes
        );
    }
1342855
static String createAuthorizationSignature(
            HttpServletRequest request, String uri, String credential,
            boolean queryAuth, boolean bothDateHeader) {
        // sort Amazon headers
        SortedSetMultimap<String, String> canonicalizedHeaders =
                TreeMultimap.create();
        for (String headerName : Collections.list(request.getHeaderNames())) {
            Collection<String> headerValues = Collections.list(
                    request.getHeaders(headerName));
            headerName = headerName.toLowerCase();
            if (!headerName.startsWith("x-amz-") || (bothDateHeader &&
                  headerName.equalsIgnoreCase(AwsHttpHeaders.DATE))) {
                continue;
            }
            if (headerValues.isEmpty()) {
                canonicalizedHeaders.put(headerName, "");
            }
            for (String headerValue : headerValues) {
                canonicalizedHeaders.put(headerName,
                        Strings.nullToEmpty(headerValue));
            }
        }

        // Build string to sign
        StringBuilder builder = new StringBuilder()
                .append(request.getMethod())
                .append('\n')
                .append(Strings.nullToEmpty(request.getHeader(
                        HttpHeaders.CONTENT_MD5)))
                .append('\n')
                .append(Strings.nullToEmpty(request.getHeader(
                        HttpHeaders.CONTENT_TYPE)))
                .append('\n');
        String expires = request.getParameter("Expires");
        if (queryAuth) {
            // If expires is not nil, then it is query string sign
            // If expires is nil, maybe also query string sign
            // So should check other accessid param, presign to judge.
            // not the expires
            builder.append(Strings.nullToEmpty(expires));
        }  else {
            if (!bothDateHeader) {
                if (canonicalizedHeaders.containsKey(AwsHttpHeaders.DATE)) {
                    builder.append("");
                } else {
                    builder.append(request.getHeader(HttpHeaders.DATE));
                }
            }  else {
                if (!canonicalizedHeaders.containsKey(AwsHttpHeaders.DATE)) {
                    builder.append(request.getHeader(AwsHttpHeaders.DATE));
                }  else {
                    // panic
                }
            }
        }

        builder.append('\n');
        for (Map.Entry<String, String> entry : canonicalizedHeaders.entries()) {
            builder.append(entry.getKey()).append(':')
                    .append(entry.getValue()).append('\n');
        }
        builder.append(uri);

        char separator = '?';
        List<String> subresources = Collections.list(
                request.getParameterNames());
        Collections.sort(subresources);
        for (String subresource : subresources) {
            if (SIGNED_SUBRESOURCES.contains(subresource)) {
                builder.append(separator).append(subresource);

                String value = request.getParameter(subresource);
                if (!"".equals(value)) {
                    builder.append('=').append(value);
                }
                separator = '&';
            }
        }

        String stringToSign = builder.toString();
        logger.trace("stringToSign: {}", stringToSign);

        // Sign string
        Mac mac;
        try {
            mac = Mac.getInstance("HmacSHA1");
            mac.init(new SecretKeySpec(credential.getBytes(
                    StandardCharsets.UTF_8), "HmacSHA1"));
        } catch (InvalidKeyException | NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        return BaseEncoding.base64().encode(mac.doFinal(
                stringToSign.getBytes(StandardCharsets.UTF_8)));
    }
564780
public function signatureB($url, $key = null, $timestamp = null)
    {
        $key = $key ?: $this->getConfig()->get('cdn_key');
        $timestamp = date('YmdHi', $timestamp ?: time());

        $parsed = parse_url($url);
        $hash = md5($key.$timestamp.$parsed['path']);

        return sprintf(
            '%s://%s/%s/%s%s',
            $parsed['scheme'], $parsed['host'], $timestamp, $hash, $parsed['path']
        );
    }
470293
public static HttpConnection connect(String requestMethod,
                                         URL url,
                                         String contentType) {
        return new HttpConnection(requestMethod, url, contentType);
    }
607408
function getStringToSign(canonicalRequest, requestDate, region) {
  if (!isString(canonicalRequest)) {
    throw new TypeError('canonicalRequest should be of type "string"')
  }
  if (!isObject(requestDate)) {
    throw new TypeError('requestDate should be of type "object"')
  }
  if (!isString(region)) {
    throw new TypeError('region should be of type "string"')
  }
  var hash = Crypto.createHash('sha256').update(canonicalRequest).digest('hex')
  var scope = getScope(region, requestDate)
  var stringToSign = []
  stringToSign.push(signV4Algorithm)
  stringToSign.push(makeDateLong(requestDate))
  stringToSign.push(scope)
  stringToSign.push(hash)
  return stringToSign.join('\n')
}
153909
public function respondToAccessTokenRequest(
        ServerRequestInterface $request,
        ResponseTypeInterface $responseType,
        DateInterval $accessTokenTTL
    ) {
        // Validate request
        $client = $this->validateClient($request);
        $encryptedAuthCode = $this->getRequestParameter('code', $request, null);

        if ($encryptedAuthCode === null) {
            throw OAuthServerException::invalidRequest('code');
        }

        try {
            $authCodePayload = json_decode($this->decrypt($encryptedAuthCode));

            $this->validateAuthorizationCode($authCodePayload, $client, $request);

            $scopes = $this->scopeRepository->finalizeScopes(
                $this->validateScopes($authCodePayload->scopes),
                $this->getIdentifier(),
                $client,
                $authCodePayload->user_id
            );
        } catch (LogicException $e) {
            throw OAuthServerException::invalidRequest('code', 'Cannot decrypt the authorization code', $e);
        }

        // Validate code challenge
        if ($this->enableCodeExchangeProof === true) {
            $codeVerifier = $this->getRequestParameter('code_verifier', $request, null);

            if ($codeVerifier === null) {
                throw OAuthServerException::invalidRequest('code_verifier');
            }

            // Validate code_verifier according to RFC-7636
            // @see: https://tools.ietf.org/html/rfc7636#section-4.1
            if (preg_match('/^[A-Za-z0-9-._~]{43,128}$/', $codeVerifier) !== 1) {
                throw OAuthServerException::invalidRequest(
                    'code_verifier',
                    'Code Verifier must follow the specifications of RFC-7636.'
                );
            }

            switch ($authCodePayload->code_challenge_method) {
                case 'plain':
                    if (hash_equals($codeVerifier, $authCodePayload->code_challenge) === false) {
                        throw OAuthServerException::invalidGrant('Failed to verify `code_verifier`.');
                    }

                    break;
                case 'S256':
                    if (
                        hash_equals(
                            strtr(rtrim(base64_encode(hash('sha256', $codeVerifier, true)), '='), '+/', '-_'),
                            $authCodePayload->code_challenge
                        ) === false
                    ) {
                        throw OAuthServerException::invalidGrant('Failed to verify `code_verifier`.');
                    }
                    // @codeCoverageIgnoreStart
                    break;
                default:
                    throw OAuthServerException::serverError(
                        sprintf(
                            'Unsupported code challenge method `%s`',
                            $authCodePayload->code_challenge_method
                        )
                    );
                // @codeCoverageIgnoreEnd
            }
        }

        // Issue and persist new access token
        $accessToken = $this->issueAccessToken($accessTokenTTL, $client, $authCodePayload->user_id, $scopes);
        $this->getEmitter()->emit(new RequestEvent(RequestEvent::ACCESS_TOKEN_ISSUED, $request));
        $responseType->setAccessToken($accessToken);

        // Issue and persist new refresh token if given
        $refreshToken = $this->issueRefreshToken($accessToken);

        if ($refreshToken !== null) {
            $this->getEmitter()->emit(new RequestEvent(RequestEvent::REFRESH_TOKEN_ISSUED, $request));
            $responseType->setRefreshToken($refreshToken);
        }

        // Revoke used auth code
        $this->authCodeRepository->revokeAuthCode($authCodePayload->auth_code_id);

        return $responseType;
    }
535346
function(method, url, timestamp) {
        var data = [method, url, this.options.publicKey, timestamp].join('|'),
            signature = crypto.sha256(this.options.privateKey, data);

        return signature;
    }
1277073
private function prepareFields(ApiContentType $contentType, $fields = null)
    {
        if ($fields !== null) {
            if (strpos($fields, ',') !== false) {
                return explode(',', $fields);
            }

            return array($fields);
        }

        $fields = array();
        $contentFields = $contentType->getFieldDefinitions();

        foreach ($contentFields as $field) {
            $fields[] = $field->identifier;
        }

        return $fields;
    }
1272973
private function _signHeader($endpoint, $authMethod, $params)
    {
        if (!is_array($params)) {
            $params = array();
        }
        if ($authMethod) {
            list($key, $value) = explode('=', substr($authMethod, 1), 2);
            $params[$key] = $value;
        }
        $baseString = '/' . $endpoint;
        ksort($params);
        foreach ($params as $key => $value) {
            $baseString .= '|' . $key . '=' . $value;
        }
        $signature = hash_hmac('sha256', $baseString, $this->_apisecret, false);

        return $signature;
    }