Calculate the signature using HMAC-SHA1
This function is copyright Andy Smith, 2007.

@param OAuthRequest request
@param string base_string
@param string consumer_secret
@param string token_secret
@return string
353965
function signature ( $request, $base_string, $consumer_secret, $token_secret )
	{
		$key = $request->urlencode($consumer_secret).'&'.$request->urlencode($token_secret);
		if (function_exists('hash_hmac'))
		{
			$signature = base64_encode(hash_hmac("sha1", $base_string, $key, true));
		}
		else
		{
		    $blocksize	= 64;
		    $hashfunc	= 'sha1';
		    if (strlen($key) > $blocksize)
		    {
		        $key = pack('H*', $hashfunc($key));
		    }
		    $key	= str_pad($key,$blocksize,chr(0x00));
		    $ipad	= str_repeat(chr(0x36),$blocksize);
		    $opad	= str_repeat(chr(0x5c),$blocksize);
		    $hmac 	= pack(
		                'H*',$hashfunc(
		                    ($key^$opad).pack(
		                        'H*',$hashfunc(
		                            ($key^$ipad).$base_string
		                        )
		                    )
		                )
		            );
			$signature = base64_encode($hmac);
		}
		return $request->urlencode($signature);
	}
248102
public void computeSignature(String requestMethod, GenericUrl requestUrl)
      throws GeneralSecurityException {
    OAuthSigner signer = this.signer;
    String signatureMethod = this.signatureMethod = signer.getSignatureMethod();
    // oauth_* parameters (except oauth_signature)
    SortedMultiset<Parameter> parameters = TreeMultiset.create();
    putParameterIfValueNotNull(parameters, "oauth_callback", callback);
    putParameterIfValueNotNull(parameters, "oauth_consumer_key", consumerKey);
    putParameterIfValueNotNull(parameters, "oauth_nonce", nonce);
    putParameterIfValueNotNull(parameters, "oauth_signature_method", signatureMethod);
    putParameterIfValueNotNull(parameters, "oauth_timestamp", timestamp);
    putParameterIfValueNotNull(parameters, "oauth_token", token);
    putParameterIfValueNotNull(parameters, "oauth_verifier", verifier);
    putParameterIfValueNotNull(parameters, "oauth_version", version);
    // parse request URL for query parameters
    for (Map.Entry<String, Object> fieldEntry : requestUrl.entrySet()) {
      Object value = fieldEntry.getValue();
      if (value != null) {
        String name = fieldEntry.getKey();
        if (value instanceof Collection<?>) {
          for (Object repeatedValue : (Collection<?>) value) {
            putParameter(parameters, name, repeatedValue);
          }
        } else {
          putParameter(parameters, name, value);
        }
      }
    }
    // normalize parameters
    StringBuilder parametersBuf = new StringBuilder();
    boolean first = true;
    for (Parameter parameter : parameters.elementSet()) {
      if (first) {
        first = false;
      } else {
        parametersBuf.append('&');
      }
      parametersBuf.append(parameter.getKey());
      String value = parameter.getValue();
      if (value != null) {
        parametersBuf.append('=').append(value);
      }
    }
    String normalizedParameters = parametersBuf.toString();
    // normalize URL, removing any query parameters and possibly port
    GenericUrl normalized = new GenericUrl();
    String scheme = requestUrl.getScheme();
    normalized.setScheme(scheme);
    normalized.setHost(requestUrl.getHost());
    normalized.setPathParts(requestUrl.getPathParts());
    int port = requestUrl.getPort();
    if ("http".equals(scheme) && port == 80 || "https".equals(scheme) && port == 443) {
      port = -1;
    }
    normalized.setPort(port);
    String normalizedPath = normalized.build();
    // signature base string
    StringBuilder buf = new StringBuilder();
    buf.append(escape(requestMethod)).append('&');
    buf.append(escape(normalizedPath)).append('&');
    buf.append(escape(normalizedParameters));
    String signatureBaseString = buf.toString();
    signature = signer.computeSignature(signatureBaseString);
  }
1358958
public static function validateSignature($uri, $nonce, $signature, $auth_token='')
    {
      $nonce = utf8_encode($nonce);
      $signature = utf8_encode($signature);
      $auth_token = utf8_encode($auth_token);
      $uri = utf8_encode($uri);
      $port = '';
      $parsed_uri = parse_url($uri);
      $base_url = $parsed_uri['scheme'].'://'.$parsed_uri['host'];
      if (isset($parsed_uri['port'])) {
        $base_url .= ':'.$parsed_uri['port'];
      }
      if (isset($parsed_uri['path'])) {
        $base_url .= $parsed_uri['path'];
      }
      $hmac = hash_hmac('SHA256', $base_url.$nonce, $auth_token, true);
      $authentication_string = base64_encode($hmac);
      return $authentication_string == $signature;
    }
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());
        }
    }
657263
public function request($method, $url, $params=array(), $token='', $secret='') {
        if (empty($token)) {
            $token = $this->access_token;
        }
        if (empty($secret)) {
            $secret = $this->access_token_secret;
        }
        // to access protected resource, sign_secret will alwasy be consumer_secret+token_secret
        $this->sign_secret = $this->consumer_secret.'&'.$secret;
        if (strtolower($method) === 'post' && !empty($params)) {
            $oauth_params = $this->prepare_oauth_parameters($url, array('oauth_token'=>$token) + $params, $method);
        } else {
            $oauth_params = $this->prepare_oauth_parameters($url, array('oauth_token'=>$token), $method);
        }
        $this->setup_oauth_http_header($oauth_params);
        $content = call_user_func_array(array($this->http, strtolower($method)), array($url, $params, $this->http_options));
        // reset http header and options to prepare for the next request
        $this->http->resetHeader();
        // return request return value
        return $content;
    }
276405
public static function generateTokenHash($host, $uri, $token, $secret)
    {
        $m0 = static::$tokenHashMagics[ord(substr($secret, -1, 1)) % 4];
        $m1 = static::$tokenHashMagics[ord(substr($secret, -2, 1)) % 4];
        $m2 = static::$tokenHashMagics[ord(substr($secret, -3, 1)) % 4];
        $m3 = static::$tokenHashMagics[ord(substr($secret, -4, 1)) % 4];

        $sha1 = sha1(
                $m0
                . $host
                . $m1
                . $uri
                . $m2
                . $token
                . $m3
                . $secret
        );

        return substr($sha1, 3, 4)
                . substr($sha1, 33, 4)
                . substr($sha1, 17, 4)
                . substr($sha1, 25, 4);
    }
952658
private static function calculate_signature( $string, $private_key ) {
		$hash = hash_hmac( 'sha1', $string, $private_key, true );

		return rawurlencode( base64_encode( $hash ) );
	}
415024
private function _sha1($data)
    {
        if (self::$_oauth_consumer_secret == null) {
            throw new \Exception('To generate a hash, the consumer secret must be set.');
        }
        if (!function_exists('hash_hmac')) {
            throw new \Exception('To generate a hash, the PHP hash extension must be available.');
        }
        return base64_encode(hash_hmac('sha1', $data, self::$_oauth_consumer_secret . '&'
            . ($this->_oauth_token_secret != null ? $this->_oauth_token_secret : ''), true));
    }
1065839
protected function _hmacSha1($request, $credentials)
    {
        $nonce = isset($credentials['nonce']) ? $credentials['nonce'] : uniqid();
        $timestamp = isset($credentials['timestamp']) ? $credentials['timestamp'] : time();
        $values = [
            'oauth_version' => '1.0',
            'oauth_nonce' => $nonce,
            'oauth_timestamp' => $timestamp,
            'oauth_signature_method' => 'HMAC-SHA1',
            'oauth_token' => $credentials['token'],
            'oauth_consumer_key' => $credentials['consumerKey'],
        ];
        $baseString = $this->baseString($request, $values);

        if (isset($credentials['realm'])) {
            $values['oauth_realm'] = $credentials['realm'];
        }
        $key = [$credentials['consumerSecret'], $credentials['tokenSecret']];
        $key = array_map([$this, '_encode'], $key);
        $key = implode('&', $key);

        $values['oauth_signature'] = base64_encode(
            hash_hmac('sha1', $baseString, $key, true)
        );

        return $this->_buildAuth($values);
    }
14944
function (auth, request, done) {
        var params = auth.get([
                'consumerKey',
                'consumerSecret',
                'token',
                'tokenSecret',
                'signatureMethod',
                'timestamp',
                'nonce',
                'version',
                'realm',
                'addParamsToHeader',
                'addEmptyParamsToSign'
            ]),
            url = urlEncoder.toNodeUrl(request.url.toString(true)),
            signatureParams,
            header;

        if (!params.consumerKey || !params.consumerSecret) {
            return done(); // Nothing to do if required parameters are not present.
        }

        // Remove existing headers and params (if any)
        request.removeHeader('Authorization');
        request.removeQueryParams(_.values(OAUTH1_PARAMS));
        request.body && request.body.urlencoded && request.body.urlencoded.remove(function (param) {
            return _.includes(_.values(OAUTH1_PARAMS), param.key);
        });

        // Generate a new nonce and timestamp
        params.nonce = params.nonce || oAuth1.nonce(11).toString();
        params.timestamp = params.timestamp || oAuth1.timestamp().toString();

        // Ensure that empty parameters are not added to the signature
        if (!params.addEmptyParamsToSign) {
            params = _.reduce(params, function (accumulator, value, key) {
                if (_.isString(value) && (value.trim() === EMPTY)) {
                    return accumulator;
                }
                accumulator[key] = value;

                return accumulator;
            }, {});
        }

        // Generate a list of parameters associated with the signature.
        signatureParams = this.computeHeader({
            url: getOAuth1BaseUrl(url),
            method: request.method,
            queryParams: request.url.query && request.url.query.count() ? request.url.query.map(function (qParam) {
                return {
                    key: qParam.key,
                    value: qParam.value
                };
            }) : [],

            // todo: WTF! figure out a better way
            // Body params only need to be included if they are URL encoded.
            // http://oauth.net/core/1.0a/#anchor13
            bodyParams: (request.body &&
                request.body.mode === RequestBody.MODES.urlencoded &&
                request.body.urlencoded &&
                request.body.urlencoded.count &&
                request.body.urlencoded.count()) ? request.body.urlencoded.map(function (formParam) {
                    return {
                        key: formParam.key,
                        value: formParam.value
                    };
                }) : [],
            helperParams: params
        });

        // The OAuth specification says that we should add parameters in the following order of preference:
        // 1. Auth Header
        // 2. Body parameters
        // 3. Query parameters
        //
        // http://oauth.net/core/1.0/#consumer_req_param
        if (params.addParamsToHeader) {
            header = oAuth1.getAuthorizationHeader(params.realm, _.map(signatureParams, function (param) {
                return [param.key, param.value];
            }));
            request.addHeader({
                key: 'Authorization',
                value: header,
                system: true
            });
        }
        else if ((/PUT|POST/).test(request.method) &&
                (request.body && request.body.mode === RequestBody.MODES.urlencoded)) {
            _.forEach(signatureParams, function (param) {
                request.body.urlencoded.add(param);
            });
        }
        else {
            request.addQueryParams(signatureParams);
        }

        return done();
    }
1166549
def _init_oauth(self, oauth_token, oauth_token_secret):
        ""
        self.oauth_token = oauth_token
        self.oauth_token_secret = oauth_token_secret

        self._oauth = OAuth1(
            self.consumer_key,
            client_secret=self.consumer_secret,
            resource_owner_key=self.oauth_token,
            resource_owner_secret=self.oauth_token_secret,
            rsa_key=self.rsa_key,
            signature_method=self._signature_method
        )
1034187
def calculate_signature key, string_to_sign
      hmac = HMAC::SHA1.new(key)
      hmac.update(string_to_sign)
      signature = Base64.encode64(hmac.digest).gsub("\n", '')
      if $DEBUG
        puts "Signature #{signature}"
      end
      signature
    end
407829
public function check_signature($request, $consumer, $token, $signature) {

        $built = $this->build_signature($request, $consumer, $token);

        // Check for zero length, although unlikely here
        if (strlen($built) == 0 || strlen($signature) == 0) {
            return false;
        }

        if (strlen($built) != strlen($signature)) {
            return false;
        }

        // Avoid a timing leak with a (hopefully) time insensitive compare
        $result = 0;
        for ($i = 0; $i < strlen($signature); $i++) {
            $result |= ord($built{$i}) ^ ord($signature{$i});
        }

        return $result == 0;

    }
777193
def signing_base(self, request, consumer, token):
        """"""
        sig = '%s&' % escape(consumer.secret)
        if token:
            sig = sig + escape(token.secret)
        return sig, sig
219326
function getSignature ({
  params,
  accessKeySecret
}) {
  const paramString = paramsToString(params)
  const stringToSign = `POST&${encodeURIComponent('/')}&${encodeURIComponent(paramString)}`

  return crypto
    .createHmac('sha1', `${accessKeySecret}&`)
    .update(stringToSign)
    .digest('base64')
}
685555
def sign_request(self, url, method, body, headers):
        
        # The use of PLAINTEXT here was copied from MAAS, but we should switch
        # to HMAC once it works server-side.
        client = oauth1.Client(
            self.consumer_key, self.consumer_secret, self.token_key,
            self.token_secret, signature_method=oauth1.SIGNATURE_PLAINTEXT,
            realm=self.realm)
        # To preserve API backward compatibility convert an empty string body
        # to `None`. The old "oauth" library would treat the empty string as
        # "no body", but "oauthlib" requires `None`.
        body = None if body is None or len(body) == 0 else body
        uri, signed_headers, body = client.sign(url, method, body, headers)
        headers.update(signed_headers)
98132
def calculate_signature(key, data, timestamp=None):
    
    # Create a timestamp if one was not given
    if timestamp is None:
        timestamp = int(time.time())

    # Construct the message from the timestamp and the data in the request
    message = str(timestamp) + ''.join("%s%s" % (k,v) for k,v in sorted(data.items()))

    # Calculate the signature (HMAC SHA256) according to RFC 2104
    signature = hmac.HMAC(str(key), message, hashlib.sha256).hexdigest()

    return signature