Validates the signature associated with the given request.
514062
def validate_signature(request, secret_key):
    

    # Extract the request parameters according to the HTTP method
    data = request.GET.copy()
    if request.method != 'GET':
        message_body = getattr(request, request.method, {})
        data.update(message_body)

    # Make sure the request contains a signature
    if data.get('sig', False):
        sig = data['sig']
        del data['sig']
    else:
        return False

    # Make sure the request contains a timestamp
    if data.get('t', False):
        timestamp = int(data.get('t', False))
        del data['t']
    else:
        return False

    # Make sure the signature has not expired
    local_time = datetime.utcnow()
    remote_time = datetime.utcfromtimestamp(timestamp)
    
    
    # this stops a bug if the client clock is ever a little ahead of 
    # the server clock.  Makes the window of acceptable time current +/- 5 mins
    if local_time > remote_time:
        delta = local_time - remote_time
    else:   
        delta = remote_time - local_time
    
    if delta.seconds > 5 * 60:  # If the signature is older than 5 minutes, it's invalid
        return False

    # Make sure the signature is valid
    return sig == calculate_signature(secret_key, data, timestamp)
490895
def validate_request(self, request):
        
        token = get_token_from_header(request)
        return self.request_validator.validate_bearer_token(
            token, request.scopes, request)
1131875
def validate_signature(self):
        """"""
        if self.signature:
            return
        self.signature = self.file.read(8)
        if self.signature != png_signature:
            raise FormatError("PNG file has invalid signature.")
327263
public boolean validateSignature(final Pair<Assertion, WsFederationConfiguration> resultPair) {
        if (resultPair == null) {
            LOGGER.warn("No assertion or its configuration was provided to validate signatures");
            return false;
        }
        val configuration = resultPair.getValue();
        val assertion = resultPair.getKey();

        if (assertion == null || configuration == null) {
            LOGGER.warn("No signature or configuration was provided to validate signatures");
            return false;
        }
        val signature = assertion.getSignature();
        if (signature == null) {
            LOGGER.warn("No signature is attached to the assertion to validate");
            return false;
        }

        try {
            LOGGER.debug("Validating the signature...");
            val validator = new SAMLSignatureProfileValidator();
            validator.validate(signature);

            val criteriaSet = new CriteriaSet();
            criteriaSet.add(new UsageCriterion(UsageType.SIGNING));
            criteriaSet.add(new EntityRoleCriterion(IDPSSODescriptor.DEFAULT_ELEMENT_NAME));
            criteriaSet.add(new ProtocolCriterion(SAMLConstants.SAML20P_NS));
            criteriaSet.add(new EntityIdCriterion(configuration.getIdentityProviderIdentifier()));
            try {
                val engine = buildSignatureTrustEngine(configuration);
                LOGGER.debug("Validating signature via trust engine for [{}]", configuration.getIdentityProviderIdentifier());
                return engine.validate(signature, criteriaSet);
            } catch (final SecurityException e) {
                LOGGER.warn(e.getMessage(), e);
            }
        } catch (final SignatureException e) {
            LOGGER.error("Failed to validate assertion signature", e);
        }

        SamlUtils.logSamlObject(this.configBean, assertion);

        LOGGER.error("Signature doesn't match any signing credential and cannot be validated.");
        return false;
    }
763646
public function signRequest($request, $token = null)
    {
        $params = $request->getData();

        if (isset($params['oauth_signature_method']) || $request->hasHeaders() && $request->getHeaders()->has('authorization')) {
            // avoid double sign of request
            return;
        }

        if (empty($params)) {
            $params = $this->generateCommonRequestParams();
        } else {
            $params = array_merge($this->generateCommonRequestParams(), $params);
        }

        $url = $request->getFullUrl();

        $signatureMethod = $this->getSignatureMethod();

        $params['oauth_signature_method'] = $signatureMethod->getName();
        $signatureBaseString = $this->composeSignatureBaseString($request->getMethod(), $url, $params);
        $signatureKey = $this->composeSignatureKey($token);
        $params['oauth_signature'] = $signatureMethod->generateSignature($signatureBaseString, $signatureKey);

        if ($this->authorizationHeaderMethods === null || in_array(strtoupper($request->getMethod()), array_map('strtoupper', $this->authorizationHeaderMethods), true)) {
            $authorizationHeader = $this->composeAuthorizationHeader($params);
            if (!empty($authorizationHeader)) {
                $request->addHeaders($authorizationHeader);

                // removing authorization header params, avoiding duplicate param server error :
                foreach ($params as $key => $value) {
                    if (substr_compare($key, 'oauth', 0, 5) === 0) {
                        unset($params[$key]);
                    }
                }
            }
        }

        $request->setData($params);
    }
1335687
public function validate(Request $request)
    {
        $this->validateTimestamp($request);
        try {
            $this->validateSignature($request);
        } catch (OutdatedCertExceptionException $e) {
            // load cert again and validate because temp file was outdatet.
            $this->validateSignature($request);
        }
    }
567755
def validate_signature(payment_transaction, callback_response)
      expected_control_code = Digest::SHA1.hexdigest(
        callback_response.status +
        callback_response.payment_paynet_id.to_s +
        callback_response.payment_client_id.to_s +
        payment_transaction.query_config.signing_key
      )

      if expected_control_code != callback_response.control_code
        raise ValidationError, "Actual control code '#{callback_response.control_code}' does " +
                               "not equal expected '#{expected_control_code}'"
      end
    end
725480
protected static void validateSignature(final DataInput input) throws IOException {
        final byte[] signatureBytes = new byte[4];
        input.readFully(signatureBytes);
        if (!Arrays.equals(ManagementProtocol.SIGNATURE, signatureBytes)) {
            throw ProtocolLogger.ROOT_LOGGER.invalidSignature(Arrays.toString(signatureBytes));
        }
    }
107271
def sign_request(self, signature_method, consumer, token):
        """"""

        if not self.is_form_encoded:
            # according to
            # http://oauth.googlecode.com/svn/spec/ext/body_hash/1.0/oauth-bodyhash.html
            # section 4.1.1 "OAuth Consumers MUST NOT include an
            # oauth_body_hash parameter on requests with form-encoded
            # request bodies."
            if not self.body:
               self.body = ''
            self['oauth_body_hash'] = base64.b64encode(sha1(to_utf8(self.body)).digest())

        if 'oauth_consumer_key' not in self:
            self['oauth_consumer_key'] = consumer.key

        if token and 'oauth_token' not in self:
            self['oauth_token'] = token.key

        self['oauth_signature_method'] = signature_method.name
        self['oauth_signature'] = signature_method.sign(self, consumer, token)
248
public static void checkFieldSignature(final String signature) {
        int pos = checkFieldTypeSignature(signature, 0);
        if (pos != signature.length()) {
            throw new IllegalArgumentException(signature + ": error at index "
                    + pos);
        }
    }
19952
def validate(self):
        
        if not self.api_token or not self.api_token_secret:
            raise ImproperlyConfigured("'api_token' and 'api_token_secret' are required for authentication.")

        if self.response_type not in ["json", "pson", "xml", "debug", None]:
            raise ImproperlyConfigured("'%s' is an invalid response_type" % self.response_type)
941543
@Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            Signature signature = new Signature();
            boolean hasRights = checkSignature(signature, request);

            if (hasRights) {
                log.info("signature-success:{}", signature);
                WebUtil.outputString(response, signature.getEchostr());
            } else {
                log.info("signature-not-match:{}", signature);
            }
        } catch (Exception e) {
            log.error("signature-error", e);
        }
    }
1261209
protected final void validateAssertionSignature(final Signature signature, final SAML2MessageContext context,
                                                    final SignatureTrustEngine engine) {

        final SAMLPeerEntityContext peerContext = context.getSAMLPeerEntityContext();

        if (signature != null) {
            final String entityId = peerContext.getEntityId();
            validateSignature(signature, entityId, engine);
        } else {
            if (wantsAssertionsSigned(context) && !peerContext.isAuthenticated()) {
                throw new SAMLSignatureRequiredException("Assertion or response must be signed");
            }
        }
    }
344806
public void verifySamlProfileRequestIfNeeded(final RequestAbstractType profileRequest,
                                                 final MetadataResolver resolver,
                                                 final HttpServletRequest request,
                                                 final MessageContext context) throws Exception {

        val roleDescriptorResolver = getRoleDescriptorResolver(resolver, context, profileRequest);

        LOGGER.debug("Validating signature for [{}]", profileRequest.getClass().getName());

        val signature = profileRequest.getSignature();
        if (signature != null) {
            validateSignatureOnProfileRequest(profileRequest, signature, roleDescriptorResolver);
        } else {
            validateSignatureOnAuthenticationRequest(profileRequest, request, context, roleDescriptorResolver);
        }
    }
1363305
public function hasValidSignature(Request $request)
    {
        $url = $request->url();

        $original = rtrim($url.'?'.Arr::query(
            Arr::except($request->query(), 'signature')
        ), '?');

        $expires = $request->query()['expires'] ?? null;

        $signature = \hash_hmac('sha256', $original, \call_user_func($this->keyResolver));

        return  \hash_equals($signature, (string) $request->query('signature', '')) &&
               ! ($expires && Carbon::now()->getTimestamp() > $expires);
    }
669541
def verify_sig(signed_request, secret, issuer=None, algorithms=None,
               expected_aud=None):
    
    if not issuer:
        issuer = _get_issuer(signed_request=signed_request)
    signed_request = _to_bytes(signed_request)
    app_req = _get_json(signed_request)

    # Check signature.
    try:
        jwt.decode(signed_request, secret, verify=True,
                   algorithms=algorithms, audience=expected_aud)
    except jwt.ExpiredSignatureError, exc:
        _re_raise_as(RequestExpired, '%s' % exc, issuer=issuer)
    except jwt.InvalidTokenError, exc:
        _re_raise_as(InvalidJWT,
                     'Signature verification failed: %s' % exc,
                     issuer=issuer)
    return app_req
1107408
def checkvalid(s, m, pk):
    
    if len(s) != b // 4:
        raise ValueError("signature length is wrong")

    if len(pk) != b // 8:
        raise ValueError("public-key length is wrong")

    s = bytearray(s)
    m = bytearray(m)
    pk = bytearray(pk)

    R = decodepoint(s[: b // 8])
    A = decodepoint(pk)
    S = decodeint(s[b // 8 : b // 4])
    h = Hint(encodepoint(R) + pk + m)

    (x1, y1, z1, t1) = P = scalarmult_B(S)
    (x2, y2, z2, t2) = Q = edwards_add(R, scalarmult(A, h))

    if (
        not isoncurve(P)
        or not isoncurve(Q)
        or (x1 * z2 - x2 * z1) % q != 0
        or (y1 * z2 - y2 * z1) % q != 0
    ):
        raise SignatureMismatch("signature does not pass verification")