Validate request signature.

        :param signature: A string signature parameter sent by weixin.
        :param timestamp: A int timestamp parameter sent by weixin.
        :param nonce: A int nonce parameter sent by weixin.
188479
def validate(self, signature, timestamp, nonce):
        
        if not self.token:
            raise RuntimeError('WEIXIN_TOKEN is missing')

        if self.expires_in:
            try:
                timestamp = int(timestamp)
            except (ValueError, TypeError):
                # fake timestamp
                return False

            delta = time.time() - timestamp
            if delta < 0:
                # this is a fake timestamp
                return False

            if delta > self.expires_in:
                # expired timestamp
                return False

        values = [self.token, str(timestamp), str(nonce)]
        s = ''.join(sorted(values))
        hsh = hashlib.sha1(s.encode('utf-8')).hexdigest()
        return signature == hsh
165154
public function makeSignature($token = null, $time = null, $nonce = null)
    {
        if (!is_string($token) || empty($token)) {
            exit("$token 参数错误");
        }

        $timestamp = !empty($time) ? $time : $_GET['timestamp'];
        $nonce     = !empty($nonce) ? $nonce : $_GET['nonce'];
        $tmpArr    = [$token, $timestamp, $nonce];
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        return $tmpStr;
    }
204467
def parse_param_signature(sig):
    
    match = PARAM_SIG_RE.match(sig.strip())
    if not match:
        raise RuntimeError('Parameter signature invalid, got ' + sig)
    groups = match.groups()
    modifiers = groups[0].split()
    typ, name, _, default = groups[-4:]
    return ParamTuple(name=name, typ=typ,
                      default=default, modifiers=modifiers)
562131
public static boolean checkSignature(String token, String signature,
                                         String timestamp, String nonce) {
        if (hasBlank(token, signature, timestamp, nonce)) {
            return false;
        }
        String[] arr = new String[]{token, timestamp, nonce};
        Arrays.sort(arr);
        StringBuilder content = new StringBuilder();
        for (String anArr : arr) {
            content.append(anArr);
        }
        MessageDigest md;
        String tmpStr = null;

        try {
            md = MessageDigest.getInstance("SHA-1");
            byte[] digest = md.digest(content.toString().getBytes("UTF-8"));
            tmpStr = byteToStr(digest);
        } catch (NoSuchAlgorithmException e) {
            LOG.error("加密方式异常", e);
        } catch (UnsupportedEncodingException e) {
            LOG.error("编码格式不支持", e);
        }
        return tmpStr != null && tmpStr.equalsIgnoreCase(signature);
    }
269237
public static boolean verifySignature(RSAPublicKey key, byte[] message, byte[] signature)
            throws InvalidKeyException, NoSuchAlgorithmException, SignatureException {
        return verifySignature(key, message, signature, DEFAULT_SIGNATURE_ALGORITHM);
    }
789985
def verify_response(self, response_json, signed_id_name='transactionid'):
        
        auth_json = response_json.get('auth', {})

        nonce = auth_json.get('nonce', '')
        timestamp = auth_json.get('timestamp', '')
        signature = binascii.unhexlify(auth_json.get('signature', ''))

        signed_id = response_json.get(signed_id_name, '')

        return self.verify_signature(signature=signature, nonce=nonce, timestamp=timestamp, signed_id=signed_id)
462803
private void verifyTimestamp(TimestampToken token, byte[] signature)
        throws NoSuchAlgorithmException, SignatureException {

        MessageDigest md =
            MessageDigest.getInstance(token.getHashAlgorithm().getName());

        if (!Arrays.equals(token.getHashedMessage(), md.digest(signature))) {
            throw new SignatureException("Signature timestamp (#" +
                token.getSerialNumber() + ") generated on " + token.getDate() +
                " is inapplicable");
        }

        if (debug != null) {
            debug.println();
            debug.println("Detected signature timestamp (#" +
                token.getSerialNumber() + ") generated on " + token.getDate());
            debug.println();
        }
    }
531431
def request_signature(self, stringtosign):
        
        digest = hmac.new(
            self.secret_key.encode(ENCODING),
            stringtosign.encode(ENCODING),
            hashlib.sha1
        ).digest()
        return b64_string(digest)
1036511
public static String generate(String encrypt, String signature, String timestamp, String nonce) {

		String format = "<xml>\n" + "<Encrypt><![CDATA[%1$s]]></Encrypt>\n"
				+ "<MsgSignature><![CDATA[%2$s]]></MsgSignature>\n"
				+ "<TimeStamp>%3$s</TimeStamp>\n" + "<Nonce><![CDATA[%4$s]]></Nonce>\n" + "</xml>";
		return String.format(format, encrypt, signature, timestamp, nonce);

	}
848235
private void validateTimestampProtocol(String protocolString, String timestampFormat, String shape2) {
        if (!StringUtils.isNullOrEmpty(timestampFormat) && isNonJsonProtocol(protocolString)) {
            throw new IllegalArgumentException(String.format(
                "Shape %s has timestamp format provided. Timestamp format for requests is not supported for xml, query or ec2 "
                + "protocol",
                shape2));

        }
    }
1301295
def decrypt_message(self, timestamp, nonce, msg_signature, encrypt_msg):
        
        signature = get_signature(self.token, timestamp, nonce, encrypt_msg)
        if signature != msg_signature:
            raise InvalidSignature(msg_signature)
        return self.prp_crypto.decrypt(encrypt_msg, self.app_id)
940240
public function validSignature($signature, $timestamp, $nonce)
    {
        if ((null == $this->tokenString) || (empty($this->tokenString))) {
            throw new Exception("error token string");
        }

        $data = array($this->tokenString, $timestamp, $nonce);
        // use SORT_STRING rule
        sort($data, SORT_STRING);
        $validStr   = '';

        foreach ($data as $v) {
            $validStr .= $v;
        }

        $validStr = sha1($validStr);
        return ($validStr === $signature);
    }
295707
def certify_timestamp(value, required=True):
    
    if certify_required(
        value=value,
        required=required,
    ):
        return

    if not isinstance(value, datetime):
        raise CertifierTypeError(
            message="expected timestamp (datetime), but value is of type {cls!r}".format(
                cls=value.__class__.__name__),
            value=value,
            required=required,
        )
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")
254083
def signature_validate_single(signature, error = None) :
    ""
    error, my_error = _get_error(error)
    result = dbus.dbus_signature_validate_single(signature.encode(), error._dbobj) != 0
    my_error.raise_if_set()
    return \
        result
1334967
public String decryptEcho(String msgSignature, String timeStamp, String nonce, String echoStr) throws AesException {
        String signature = SHA1.getSHA1(token, timeStamp, nonce, echoStr);

        if (!signature.equals(msgSignature)) {
            throw new AesException(AesException.ValidateSignatureError);
        }

        return decrypt(echoStr);
    }
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)