Step 3 of the AWS Signature version 4 calculation. It involves deriving
the signing key and computing the signature. Refer to
http://docs.aws.amazon
.com/general/latest/gr/sigv4-calculate-signature.html
492229
private final byte[] deriveSigningKey(AWSCredentials credentials,
            AWS4SignerRequestParams signerRequestParams) {

        final String cacheKey = computeSigningCacheKeyName(credentials,
                signerRequestParams);
        final long daysSinceEpochSigningDate = DateUtils
                .numberOfDaysSinceEpoch(signerRequestParams
                        .getSigningDateTimeMilli());

        SignerKey signerKey = signerCache.get(cacheKey);

        if (signerKey != null) {
            if (daysSinceEpochSigningDate == signerKey
                    .getNumberOfDaysSinceEpoch()) {
                return signerKey.getSigningKey();
            }
        }
        if (log.isDebugEnabled()) {
            log.debug("Generating a new signing key as the signing key not available in the cache for the date "
                    + TimeUnit.DAYS.toMillis(daysSinceEpochSigningDate));
        }
        byte[] signingKey = newSigningKey(credentials,
                signerRequestParams.getFormattedSigningDate(),
                signerRequestParams.getRegionName(),
                signerRequestParams.getServiceName());
        signerCache.add(cacheKey, new SignerKey(
                daysSinceEpochSigningDate, signingKey));
        return signingKey;
    }
230001
function getSignerClass(request) {
    var version;
    // get operation authtype if present
    var operation = null;
    var authtype = '';
    if (request) {
      var operations = request.service.api.operations || {};
      operation = operations[request.operation] || null;
      authtype = operation ? operation.authtype : '';
    }
    if (this.config.signatureVersion) {
      version = this.config.signatureVersion;
    } else if (authtype === 'v4' || authtype === 'v4-unsigned-body') {
      version = 'v4';
    } else {
      version = this.api.signatureVersion;
    }
    return AWS.Signers.RequestSigner.getVersion(version);
  }
373444
def sign(self, identity, digest):
        """"""
        log.info('please confirm GPG signature on %s for "%s"...',
                 self.device, identity.to_string())
        if identity.curve_name == formats.CURVE_NIST256:
            digest = digest[:32]  # sign the first 256 bits
        log.debug('signing digest: %s', util.hexlify(digest))
        with self.device:
            sig = self.device.sign(blob=digest, identity=identity)
        return (util.bytes2num(sig[:32]), util.bytes2num(sig[32:]))
1281605
protected final byte[] computeSignature(String stringToSign,
            byte[] signingKey, AWS4SignerRequestParams signerRequestParams) {
        return sign(stringToSign.getBytes(Charset.forName("UTF-8")), signingKey,
                SigningAlgorithm.HmacSHA256);
    }
338541
def _self_signed(cert):
    

    self_signed = cert.self_signed

    if self_signed == 'yes':
        return True
    if self_signed == 'no':
        return False

    # In the case of "maybe", we have to check the signature
    signature_algo = cert['signature_algorithm'].signature_algo
    hash_algo = cert['signature_algorithm'].hash_algo

    if signature_algo == 'rsassa_pkcs1v15':
        verify_func = asymmetric.rsa_pkcs1v15_verify
    elif signature_algo == 'dsa':
        verify_func = asymmetric.dsa_verify
    elif signature_algo == 'ecdsa':
        verify_func = asymmetric.ecdsa_verify
    else:
        raise PathValidationError(pretty_message(
            '''
            Unable to verify the signature of the certificate since it uses
            the unsupported algorithm %s
            ''',
            signature_algo
        ))

    try:
        key_object = asymmetric.load_certificate(cert)
        verify_func(key_object, cert['signature_value'].native, cert['tbs_certificate'].dump(), hash_algo)
        return True

    except (oscrypto.errors.SignatureError):
        return False
31085
def _get_v4_signed_headers(self):
        """"""
        if self.aws_session is None:
            boto_session = session.Session()
            creds = boto_session.get_credentials()
        else:
            creds = self.aws_session.get_credentials()
        if creds is None:
            raise CerberusClientException("Unable to locate AWS credentials")
        readonly_credentials = creds.get_frozen_credentials()

        # hardcode get-caller-identity request
        data = OrderedDict((('Action','GetCallerIdentity'), ('Version', '2011-06-15')))
        url = 'https://sts.{}.amazonaws.com/'.format(self.region)
        request_object = awsrequest.AWSRequest(method='POST', url=url, data=data)

        signer = auth.SigV4Auth(readonly_credentials, 'sts', self.region)
        signer.add_auth(request_object)
        return request_object.headers
966355
def _compute_signature(parameters, access_key_secret):
    '''
    
    '''

    def percent_encode(line):
        if not isinstance(line, six.string_types):
            return line

        s = line
        if sys.stdin.encoding is None:
            s = line.decode().encode('utf8')
        else:
            s = line.decode(sys.stdin.encoding).encode('utf8')
        res = _quote(s, '')
        res = res.replace('+', '%20')
        res = res.replace('*', '%2A')
        res = res.replace('%7E', '~')
        return res

    sortedParameters = sorted(list(parameters.items()), key=lambda items: items[0])

    canonicalizedQueryString = ''
    for k, v in sortedParameters:
        canonicalizedQueryString += '&' + percent_encode(k) \
            + '=' + percent_encode(v)

    # All aliyun API only support GET method
    stringToSign = 'GET&%2F&' + percent_encode(canonicalizedQueryString[1:])

    h = hmac.new(to_bytes(access_key_secret + "&"), stringToSign, sha1)
    signature = base64.encodestring(h.digest()).strip()
    return signature
441491
def verify(self, signature):
        
        prehashed_digest = self._hasher.finalize()
        self.key.verify(
            signature=signature,
            data=prehashed_digest,
            signature_algorithm=ec.ECDSA(Prehashed(self.algorithm.signing_hash_type())),
        )
735037
def calculate_hmac(cls, params):
        
        encoded_params = cls.__encoded_params_for_signature(params)
        # Generate the hex digest for the sorted parameters using the secret.
        return hmac.new(cls.secret.encode(), encoded_params.encode(), sha256).hexdigest()
484189
def sign(self, message, privkey, secret):
        
        m = self.GFn.value(message)
        x = self.GFn.value(privkey)
        k = self.GFn.value(secret)

        R = self.G * k

        r = self.GFn.value(R.x)
        s = (m + x * r) / k

        return (r, s)
520975
def verify(self, secret_key):
        
        verification_input = NotificationMessage.SERVICE_NAME
        verification_input += NotificationMessage.OPERATION_NAME
        verification_input += self.timestamp
        h = hmac.new(key=secret_key, digestmod=sha)
        h.update(verification_input)
        signature_calc = base64.b64encode(h.digest())
        return self.signature == signature_calc
571687
def calculate_signature(self, node, sign=True):
        
        signed_info_xml = node.find('ds:SignedInfo',
                                    namespaces=constants.NS_MAP)
        canonicalization_method = signed_info_xml.find(
            'ds:CanonicalizationMethod', namespaces=constants.NS_MAP
        ).get('Algorithm')
        signature_method = signed_info_xml.find(
            'ds:SignatureMethod', namespaces=constants.NS_MAP
        ).get('Algorithm')
        if signature_method not in constants.TransformUsageSignatureMethod:
            raise Exception('Method ' + signature_method + ' not accepted')
        signature = constants.TransformUsageSignatureMethod[signature_method]
        signed_info = self.canonicalization(
            canonicalization_method, signed_info_xml
        )
        if not sign:
            signature_value = node.find('ds:SignatureValue',
                                        namespaces=constants.NS_MAP).text
            public_key = signature['method'].get_public_key(node, self)
            signature['method'].verify(
                signature_value,
                signed_info,
                public_key,
                signature['digest']
            )
        else:
            node.find(
                'ds:SignatureValue', namespaces=constants.NS_MAP
            ).text = b64_print(base64.b64encode(
                signature['method'].sign(
                    signed_info,
                    self.private_key,
                    signature['digest']
                )
            ))
1499
function _sign($key, $signatureAlgorithm)
    {
        if ($key instanceof RSA) {
            switch ($signatureAlgorithm) {
                case 'md2WithRSAEncryption':
                case 'md5WithRSAEncryption':
                case 'sha1WithRSAEncryption':
                case 'sha224WithRSAEncryption':
                case 'sha256WithRSAEncryption':
                case 'sha384WithRSAEncryption':
                case 'sha512WithRSAEncryption':
                    $key->setHash(preg_replace('#WithRSAEncryption$#', '', $signatureAlgorithm));
                    $key->setSignatureMode(RSA::SIGNATURE_PKCS1);

                    $this->currentCert['signature'] = base64_encode("\0" . $key->sign($this->signatureSubject));
                    return $this->currentCert;
            }
        }

        return false;
    }
98662
function genOAuthSig (options) {

    log(options.verbose,"Now generating OAuth sig ...");

    // Build an array of all the parameters we need to include in the signature.
    // Signature parameters are in the format {key,value}, both the key and the
    // value need to be RFC3986 percent encoded.

    var sigParams  = [];

    if ( options.queryParams ) {
        Object.keys(options.queryParams).forEach(function (key) {
            sigParams.push(createEncodedParam(key,options.queryParams[key]));
        });
    }

    sigParams.push(createEncodedParam("oauth_consumer_key",options.oAuthConsumerKey));
    sigParams.push(createEncodedParam("oauth_nonce",options.oAuthNonce));
    sigParams.push(createEncodedParam("oauth_signature_method",options.oAuthSignatureMethod));
    sigParams.push(createEncodedParam("oauth_timestamp",options.oAuthTimestamp));
    sigParams.push(createEncodedParam("oauth_token",options.oAuthToken));
    sigParams.push(createEncodedParam("oauth_version",options.oAuthVersion));

    // Parameters need to be sorted alphabetically based on the encoded key.

    sigParams.sort(function (a,b) {
        if ( a.key < b.key ) {
            return -1;
        } else if ( a.key > b.key ) {
            return 1;
        } else {
            return 0;
        }
    });

    // Build the signature parameter string from the sorted array.

    var sigParamsString = "";

    log(options.verbose,"Ordered percent encoded sig params are:");

    for ( var i=0; i<sigParams.length; i++ ) {
        sigParamsString += sigParams[i].key+"="+sigParams[i].value;
        log(options.verbose,"  "+sigParams[i].key+"="+sigParams[i].value);
        if ( sigParams[i+1] ) {
            sigParamsString += "&";
        }
    }

    log(options.verbose,"Generated sig params string: "+sigParamsString);

    // Build the base signature string from the HTTP method, base URL and signature
    // parameter string.

    var sigBaseString = options.method.toUpperCase()+"&";
    sigBaseString += percentEncode(options.baseURL)+"&";
    sigBaseString += percentEncode(sigParamsString);

    log(options.verbose,"Generated base sig string: "+sigBaseString);

    // Generate the signing key from the consumer secret and oAuth token secret.

    var signingKey = options.oAuthConsumerSecret+"&"+options.oAuthTokenSecret;

    log(options.verbose,"Generated HMAC-SHA1 signing key: "+signingKey);

    // The final value for the OAuth signature is the HMAC-SHA1 hash of the
    // signing key and the base sig string, all base64 encoded.

    var oAuthSig = crypto.createHmac("sha1",signingKey).update(sigBaseString).digest("base64");

    log(options.verbose,"OAuth sig is: "+oAuthSig);

    return oAuthSig;
}
712052
def calculated_sign
      params = SIGN_PARAMS.each_with_object({}) do |p, h|
        h[p] = send(p).tap { |v| v ? v.to_s : nil }
      end
      Signature.new(params, @secret).sign.upcase
    end
789805
def combine_signatures(*sig_dicts)
      combined = {}
      sig_dicts.each do |sig_dict|
        sig_dict.each do |tree, signature|
          decoded_sig = decode_base58(signature)
          low_s_der_sig = Bitcoin::Script.is_low_der_signature?(decoded_sig) ?
            decoded_sig : Bitcoin::OpenSSL_EC.signature_to_low_s(decoded_sig)
          combined[tree] = Bitcoin::OpenSSL_EC.repack_der_signature(low_s_der_sig)
        end
      end

      # Order of signatures is important for validation, so we always
      # sort public keys and signatures by the name of the tree
      # they belong to.
      combined.sort_by { |tree, value| tree }.map { |tree, sig| sig }
    end
1226650
def compute(self):
        """"""
        if "Signature" in self.params:
            raise RuntimeError("Existing signature in parameters")
        if self.signature_version is not None:
            version = self.signature_version
        else:
            version = self.params["SignatureVersion"]
        if str(version) == "1":
            bytes = self.old_signing_text()
            hash_type = "sha1"
        elif str(version) == "2":
            bytes = self.signing_text()
            if self.signature_method is not None:
                signature_method = self.signature_method
            else:
                signature_method = self.params["SignatureMethod"]
            hash_type = signature_method[len("Hmac"):].lower()
        else:
            raise RuntimeError("Unsupported SignatureVersion: '%s'" % version)
        return self.creds.sign(bytes, hash_type)