/* Create an Array of required parameters, sort them
Calculate signature and invoke the POST to the MWS Service URL

@param AWSAccessKeyId [String]
@param Version [String]
@param SignatureMethod [String]
@param Timestamp [String]
@param Signature [String]
172613
private function calculateSignatureAndParametersToString($parameters = array())
    {
        foreach ($parameters as $key => $value) {
            // Ensure that no unexpected type coercions have happened
            if ($key === 'CaptureNow' || $key === 'ConfirmNow' || $key === 'InheritShippingAddress' || $key === 'RequestPaymentAuthorization') {
                if (!is_bool($value)) {
                    throw new \Exception($key . ' value ' . $value . ' is of type ' . gettype($value) . ' and should be a boolean value');
                }
            }

            // Ensure boolean values are outputed as 'true' or 'false'
            if (is_bool($value)) {
                $parameters[$key] = json_encode($value);
            }
        }

        $parameters['AWSAccessKeyId']   = $this->config['access_key'];
        $parameters['Version']          = self::MWS_VERSION;
        $parameters['SignatureMethod']  = 'HmacSHA256';
        $parameters['SignatureVersion'] = 2;
        $parameters['Timestamp']        = $this->getFormattedTimestamp();
        uksort($parameters, 'strcmp');

        $this->createServiceUrl();

        $parameters['Signature'] = $this->signParameters($parameters);
        $parameters              = $this->getParametersAsString($parameters);

        // Save these parameters in the parameters variable so that it can be returned for unit testing.
        $this->parameters = $parameters;

        return $parameters;
    }
995369
public String computeSignature(String requestMethod, String targetUrl, Map<String, String> params, @Sensitive String consumerSecret, @Sensitive String tokenSecret) {

        String signatureBaseString = createSignatureBaseString(requestMethod, targetUrl, params);

        // Hash the base string using the consumer secret (and request token secret, if known) as a key
        String signature = "";
        try {
            String secretToEncode = null;
            if (consumerSecret != null) {
                secretToEncode = consumerSecret;
            }
            StringBuilder keyString = new StringBuilder(Utils.percentEncodeSensitive(secretToEncode)).append("&");
            if (tokenSecret != null) {
                keyString.append(Utils.percentEncodeSensitive(tokenSecret));
            }
            signature = computeSha1Signature(signatureBaseString, keyString.toString());

        } catch (GeneralSecurityException e) {
            Tr.warning(tc, "TWITTER_ERROR_CREATING_SIGNATURE", new Object[] { e.getLocalizedMessage() });
        } catch (UnsupportedEncodingException e) {
            // Should be using UTF-8 encoding, so this should be highly unlikely
            if (tc.isDebugEnabled()) {
                Tr.debug(tc, "Caught unexpected exception: " + e.getLocalizedMessage(), e);
            }
        }

        return signature;
    }
551348
@Override
    public void sign ( byte[] data, int offset, int length, CommonServerMessageBlock request, CommonServerMessageBlock response ) {
        if ( log.isTraceEnabled() ) {
            log.trace("Signing with seq " + this.signSequence);
        }

        ( (ServerMessageBlock) request ).setSignSeq(this.signSequence);
        if ( response != null ) {
            ( (ServerMessageBlock) response ).setSignSeq(this.signSequence + 1);
        }

        try {
            update(this.macSigningKey, 0, this.macSigningKey.length);
            int index = offset + SmbConstants.SIGNATURE_OFFSET;
            for ( int i = 0; i < 8; i++ )
                data[ index + i ] = 0;
            SMBUtil.writeInt4(this.signSequence, data, index);
            update(data, offset, length);
            System.arraycopy(digest(), 0, data, index, 8);
            if ( this.bypass ) {
                this.bypass = false;
                System.arraycopy("BSRSPYL ".getBytes(), 0, data, index, 8);
            }
        }
        catch ( Exception ex ) {
            log.error("Signature failed", ex);
        }
        finally {
            if ( request instanceof SmbComNtCancel ) {
                this.signSequence++;
            }
            else {
                this.signSequence += 2;
            }
        }
    }
752579
private static String createSignature(String     stringToSign,
                                          String     awsSecretKey,
                                          String     algorithm)
            throws SignatureException {

        assert stringToSign != null;
        assert awsSecretKey != null;
        assert algorithm != null;

        String signature;

        try {
            byte[] secretyKeyBytes = awsSecretKey.getBytes(UTF8_CHARSET);
            SecretKeySpec secretKeySpec = new SecretKeySpec(secretyKeyBytes,
                                                            algorithm);
            Mac mac = Mac.getInstance(algorithm);
            mac.init(secretKeySpec);

            byte[] data = stringToSign.getBytes(UTF8_CHARSET);

            byte[] rawHmac = mac.doFinal(data);
            signature = rfc3986Conformance(new String(Codec.base64Encode(rawHmac)));
        } catch (Exception e) {
            throw new SignatureException("Failed to generate HMAC : " +
                                                               e.getMessage());
        }

        return signature;
    }
19765
def sign_request(method, uri, form_args)
      # Convert non-string keys to strings so the sort works
      args = {}
      if form_args
        form_args.each do |key, value|
          next unless value and value != ""

          key = key.to_s unless key.is_a?(String)
          args[key] = value
        end
      end

      # Add the necessary OAuth args
      args["oauth_version"] = "1.0"
      args["oauth_consumer_key"] = @config[:api_key]
      args["oauth_nonce"] = Digest::MD5.hexdigest("#{Time.now.to_f}#{rand(10 ** 30)}")
      args["oauth_signature_method"] = "HMAC-SHA1"
      args["oauth_timestamp"] = Time.now.utc.to_i
      args["oauth_token"] = @config[:user][:token]

      # RFC 1738 (http://www.ietf.org/rfc/rfc1738.txt) says:
      #
      #     Thus, only alphanumerics, the special characters "$-_.+!*'(),", and
      #     reserved characters used for their reserved purposes may be used
      #     unencoded within a URL.
      #
      # However, if we don't escape apostrophes and parentheses the SmugMug API fails
      # with an invalid signature error:
      #
      #     Error #35, invalid signature (SmugMug::OAuthError)
      #
      # To overcome this, define a new unreserved character list and use this in URI::escape
      unreserved = "\\-_.!~*a-zA-Z\\d"
      unsafe = Regexp.new("[^#{unreserved}]", false, 'N')

      # Sort the params
      sorted_args = []
      args.sort.each do |key, value|
        sorted_args.push("#{key.to_s}=#{URI::escape(value.to_s, unsafe)}")
      end

      postdata = sorted_args.join("&")

      # Final string to hash
      sig_base = "#{method}&#{URI::escape("#{uri.scheme}://#{uri.host}#{uri.path}", unsafe)}&#{URI::escape(postdata, unsafe)}"

      signature = OpenSSL::HMAC.digest(@digest, "#{@config[:oauth_secret]}&#{@config[:user][:secret]}", sig_base)
      signature = URI::escape(Base64.encode64(signature).chomp, unsafe)

      if uri == API_URI
        "#{postdata}&oauth_signature=#{signature}"
      else
        args["oauth_signature"] = signature
        args
      end
    end
34312
@Override
    protected void processRequestPayload(SignableRequest<?> request, byte[] signature,
            byte[] signingKey, AWS4SignerRequestParams signerRequestParams) {
        if (useChunkEncoding(request)) {
            AwsChunkedEncodingInputStream chunkEncodededStream = new AwsChunkedEncodingInputStream(
                    request.getContent(), signingKey,
                    signerRequestParams.getFormattedSigningDateTime(),
                    signerRequestParams.getScope(),
                    BinaryUtils.toHex(signature), this);
            request.setContent(chunkEncodededStream);
        }
    }
1028143
def generate_signature(method, version, endpoint,
                       date, rel_url, content_type, content,
                       access_key, secret_key, hash_type):
    '''
    
    '''
    hash_type = hash_type
    hostname = endpoint._val.netloc  # FIXME: migrate to public API
    if version >= 'v4.20181215':
        content = b''
    else:
        if content_type.startswith('multipart/'):
            content = b''
    body_hash = hashlib.new(hash_type, content).hexdigest()

    sign_str = '{}\n{}\n{}\nhost:{}\ncontent-type:{}\nx-backendai-version:{}\n{}'.format(  # noqa
        method.upper(),
        rel_url,
        date.isoformat(),
        hostname,
        content_type.lower(),
        version,
        body_hash
    )
    sign_bytes = sign_str.encode()

    sign_key = hmac.new(secret_key.encode(),
                        date.strftime('%Y%m%d').encode(), hash_type).digest()
    sign_key = hmac.new(sign_key, hostname.encode(), hash_type).digest()

    signature = hmac.new(sign_key, sign_bytes, hash_type).hexdigest()
    headers = {
        'Authorization': 'BackendAI signMethod=HMAC-{}, credential={}:{}'.format(
            hash_type.upper(),
            access_key,
            signature
        ),
    }
    return headers, signature
320669
private byte[] signRaw(BoxSignatureAlgorithm algorithm, String key, String webHookPayload,
            String deliveryTimestamp) {
        Mac mac = MAC_POOL.acquire(algorithm.javaProviderName);
        try {
            mac.init(new SecretKeySpec(key.getBytes(UTF_8), algorithm.javaProviderName));
            mac.update(UTF_8.encode(webHookPayload));
            mac.update(UTF_8.encode(deliveryTimestamp));
            return mac.doFinal();
        } catch (InvalidKeyException e) {
            throw new IllegalArgumentException("Invalid key: ", e);
        } finally {
            MAC_POOL.release(mac);
        }
    }
560686
@Override
    public synchronized void sign ( byte[] data, int offset, int length, CommonServerMessageBlock request, CommonServerMessageBlock response ) {
        this.digest.reset();

        // zero out signature field
        int index = offset + SIGNATURE_OFFSET;
        for ( int i = 0; i < SIGNATURE_LENGTH; i++ )
            data[ index + i ] = 0;

        // set signed flag
        int oldFlags = SMBUtil.readInt4(data, offset + 16);
        int flags = oldFlags | ServerMessageBlock2.SMB2_FLAGS_SIGNED;
        SMBUtil.writeInt4(flags, data, offset + 16);

        this.digest.update(data, offset, length);

        byte[] sig = this.digest.doFinal();
        System.arraycopy(sig, 0, data, offset + SIGNATURE_OFFSET, SIGNATURE_LENGTH);
    }
1026305
public static void checkMethodSignature(final String signature) {
        // MethodTypeSignature:
        // FormalTypeParameters? ( TypeSignature* ) ( TypeSignature | V ) (
        // ^ClassTypeSignature | ^TypeVariableSignature )*

        int pos = 0;
        if (getChar(signature, 0) == '<') {
            pos = checkFormalTypeParameters(signature, pos);
        }
        pos = checkChar('(', signature, pos);
        while ("ZCBSIFJDL[T".indexOf(getChar(signature, pos)) != -1) {
            pos = checkTypeSignature(signature, pos);
        }
        pos = checkChar(')', signature, pos);
        if (getChar(signature, pos) == 'V') {
            ++pos;
        } else {
            pos = checkTypeSignature(signature, pos);
        }
        while (getChar(signature, pos) == '^') {
            ++pos;
            if (getChar(signature, pos) == 'L') {
                pos = checkClassTypeSignature(signature, pos);
            } else {
                pos = checkTypeVariableSignature(signature, pos);
            }
        }
        if (pos != signature.length()) {
            throw new IllegalArgumentException(signature + ": error at index "
                    + pos);
        }
    }
1080270
function Signature(req, buf) {
  this.req = req;
  this.rawBody = buf || req.rawBody;

  this.xSignature = (req.headers['x-signature'] || '').split(' ');
  this.signature = base64url.toBuffer(this.xSignature[0] || '');
  this.publicKey = base64url.toBuffer(this.xSignature[1] || '');
  this.endorsement = base64url.toBuffer(this.xSignature[2] || '');

  this.date = Date.parse(req.headers.date);
}
1352608
public static HttpUrl presignV4(Request request, String region, String accessKey, String secretKey, int expires)
    throws NoSuchAlgorithmException, InvalidKeyException {
    String contentSha256 = "UNSIGNED-PAYLOAD";
    DateTime date = DateFormat.AMZ_DATE_FORMAT.parseDateTime(request.header("x-amz-date"));

    Signer signer = new Signer(request, contentSha256, date, region, accessKey, secretKey, null);
    signer.setScope();
    signer.setPresignCanonicalRequest(expires);
    signer.setStringToSign();
    signer.setSigningKey();
    signer.setSignature();

    return signer.url.newBuilder()
        .addEncodedQueryParameter(S3Escaper.encode("X-Amz-Signature"), S3Escaper.encode(signer.signature))
        .build();
  }
235148
public static String credential(String accessKey, DateTime date, String region) {
    return accessKey + "/" + date.toString(DateFormat.SIGNER_DATE_FORMAT) + "/" + region + "/s3/aws4_request";
  }
58183
private void addPreSignInformationToRequest(SignableRequest<?> request,
            AWSCredentials credentials, AWS4SignerRequestParams signerParams,
            String timeStamp, long expirationInSeconds) {

        String signingCredentials = credentials.getAWSAccessKeyId() + "/"
                + signerParams.getScope();

        request.addParameter(X_AMZ_ALGORITHM, AWS4_SIGNING_ALGORITHM);
        request.addParameter(X_AMZ_DATE, timeStamp);
        request.addParameter(X_AMZ_SIGNED_HEADER,
                getSignedHeadersString(request));
        request.addParameter(X_AMZ_EXPIRES,
                Long.toString(expirationInSeconds));
        request.addParameter(X_AMZ_CREDENTIAL, signingCredentials);
    }
17162
function SignatureBaseString(httpMethod, url, parameters) {
		parameters = new ParametersLoader(parameters).get();
		this._httpMethod = new HttpMethodElement(httpMethod).get();
		this._url = new UrlElement(url).get();
		this._parameters = new ParametersElement(parameters).get();
		this._rfc3986 = new Rfc3986();
	}
1238861
function signRequest(method, url, params, secret){
    //
    // normalize request method
    method = method.toUpperCase();
    if(!(method === 'POST' || method === 'GET')){
        throw new Error('Request method should either Post or Get and you passed "' + method + '"');
    }
    params = params || {};
    //
    // form the parameters string
    var paramStr = '';
    var keys = [];
    for(v in params){
        keys.push(v);
    }
    keys.sort();
    for(var i = 0; i < keys.length; i++){
        paramStr += keys[i] + '=' + params[keys[i]];
    }
    var basicString = method + url + paramStr + secret;
    //console.log('basic string: ' + basicString);
    var encoded = URLEncode(basicString);

    var md5 = crypto.createHash('md5');
    md5.update(encoded);
    var sign = md5.digest('hex');
    var body = '';
    for(v in params){
        body += URLEncode(v) + '=' + URLEncode(params[v]) + '&';
    }
    body += 'sign=' + sign; //append the signature
    return body;
}
535346
function(method, url, timestamp) {
        var data = [method, url, this.options.publicKey, timestamp].join('|'),
            signature = crypto.sha256(this.options.privateKey, data);

        return signature;
    }