當前位置: 首頁>>代碼示例>>Python>>正文


Python hmac.compare_digest方法代碼示例

本文整理匯總了Python中hmac.compare_digest方法的典型用法代碼示例。如果您正苦於以下問題:Python hmac.compare_digest方法的具體用法?Python hmac.compare_digest怎麽用?Python hmac.compare_digest使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在hmac的用法示例。


在下文中一共展示了hmac.compare_digest方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: verify_slack_requests

# 需要導入模塊: import hmac [as 別名]
# 或者: from hmac import compare_digest [as 別名]
def verify_slack_requests(f=None):
    """
    Verify the request signature of the request sent from Slack
    Generate a new hash using the app's signing secret and request data
    """
    @wraps(f)
    def wrapper(*args, **kwargs):
        signature = request.headers['X-Slack-Signature']
        timestamp = request.headers['X-Slack-Request-Timestamp']
        data = request.data.decode('utf-8')
        # data = urllib.parse.urlencode(urllib.parse.unquote(raw_string))

        format_req = str.encode(f"v0:{timestamp}:{data}")
        encoded_secret = str.encode(config.SLACK_SECRET)
        request_hash = hmac.new(encoded_secret, format_req, hashlib.sha256).hexdigest()
        calculated_signature = f"v0={request_hash}"
        if hmac.compare_digest(calculated_signature, signature):
            return f(*args, **kwargs)

        return make_response(jsonify({'message': 'Invalid auth'})), 401
    return wrapper 
開發者ID:teamsempo,項目名稱:SempoBlockchain,代碼行數:23,代碼來源:auth.py

示例2: validate

# 需要導入模塊: import hmac [as 別名]
# 或者: from hmac import compare_digest [as 別名]
def validate(self):
        rv = BaseForm.validate(self)
        if not rv:
            return False

        if current_user.name in self.password.data:
            self.password.errors.append(ERROR_PASSWORD_CONTAINS_USERNAME)
            return False

        if self.password.data != self.password_repeat.data:
            self.password_repeat.errors.append(ERROR_PASSWORD_REPEAT_MISMATCHES)
            return False

        if not compare_digest(current_user.password, hash_password(self.password_current.data, current_user.salt)):
            self.password_current.errors.append(ERROR_PASSWORD_INCORRECT)
            return False

        return True 
開發者ID:archlinux,項目名稱:arch-security-tracker,代碼行數:20,代碼來源:user.py

示例3: validate

# 需要導入模塊: import hmac [as 別名]
# 或者: from hmac import compare_digest [as 別名]
def validate(self):
        self.user = None
        rv = BaseForm.validate(self)
        if not rv:
            return False

        def fail():
            self.password.errors.append(ERROR_INVALID_USERNAME_PASSWORD)
            return False

        user = User.query.filter(User.name == self.username.data).first()
        if not user:
            compare_digest(dummy_password, hash_password(self.password.data, 'the cake is a lie!'))
            return fail()
        if not compare_digest(user.password, hash_password(self.password.data, user.salt)):
            return fail()
        if not user.active:
            self.username.errors.append(ERROR_ACCOUNT_DISABLED)
            return False
        self.user = user
        return True 
開發者ID:archlinux,項目名稱:arch-security-tracker,代碼行數:23,代碼來源:login.py

示例4: validate_signature

# 需要導入模塊: import hmac [as 別名]
# 或者: from hmac import compare_digest [as 別名]
def validate_signature(request):
    """Validate that the signature in the header matches the payload."""
    if CONFIG["SECRET"] is None:
        return
    try:
        signature = request.headers["X-Hub-Signature"]
        hashname, hashval = signature.split("=")
    except (KeyError, ValueError):
        raise BadRequestError()

    if (hashname in CONFIG["HASHLIB_BLACKLIST"]) or (
        hashname not in hashlib.algorithms_available
    ):
        raise BadRequestError("X-Hub-Signature hash algorithm unavailable")

    digest = hmac.new(
        CONFIG["SECRET"].encode(), request.raw_body.encode(), hashname
    ).hexdigest()
    if not hmac.compare_digest(digest.encode(), hashval.encode("utf-8")):
        raise UnauthorizedError("X-Hub-Signature mismatch") 
開發者ID:FussyFox,項目名稱:github-webhook-lambda,代碼行數:22,代碼來源:app.py

示例5: verify_signature

# 需要導入模塊: import hmac [as 別名]
# 或者: from hmac import compare_digest [as 別名]
def verify_signature(self, body, signature, key):
        if sys.version_info[0] == 3:  # pragma: no cover
            key = bytes(key, 'utf-8')
            body = bytes(body, 'utf-8')

        dig = hmac.new(key=key,
                       msg=body,
                       digestmod=hashlib.sha256)

        generated_signature = dig.hexdigest()

        if sys.version_info[0:3] < (2, 7, 7):
            result = self.compare_string(generated_signature, signature)
        else:
            result = hmac.compare_digest(generated_signature, signature)

        if not result:
            raise SignatureVerificationError(
                'Razorpay Signature Verification Failed')
        return result

    # Taken from Django Source Code
    # Used in python version < 2.7.7
    # As hmac.compare_digest is not present in prev versions 
開發者ID:razorpay,項目名稱:razorpay-python,代碼行數:26,代碼來源:utility.py

示例6: authentification

# 需要導入模塊: import hmac [as 別名]
# 或者: from hmac import compare_digest [as 別名]
def authentification(request: requests.Request):
    # Only SHA1 is supported
    header_signature = request.headers.get("X-Hub-Signature")
    if header_signature is None:
        LOG.warning("Webhook without signature")
        raise fastapi.HTTPException(status_code=403)

    try:
        sha_name, signature = header_signature.split("=")
    except ValueError:
        sha_name = None

    if sha_name != "sha1":
        LOG.warning("Webhook signature malformed")
        raise fastapi.HTTPException(status_code=403)

    body = await request.body()
    mac = utils.compute_hmac(body)
    if not hmac.compare_digest(mac, str(signature)):
        LOG.warning("Webhook signature invalid")
        raise fastapi.HTTPException(status_code=403) 
開發者ID:Mergifyio,項目名稱:mergify-engine,代碼行數:23,代碼來源:web.py

示例7: post

# 需要導入模塊: import hmac [as 別名]
# 或者: from hmac import compare_digest [as 別名]
def post(self, hook, action, app, env, digest):
        expected = hmac.new(
            current_app.config["API_KEY"].encode("utf8"),
            f"{hook}/{action}/{app}/{env}".encode("utf8"),
            sha256,
        ).hexdigest()
        if not hmac.compare_digest(expected, digest):
            return self.respond(status_code=403)

        try:
            hook = hooks.get(hook)
        except InvalidHook:
            return self.respond("Invalid hook", status_code=404)

        if action != "deploy":
            return self.respond("Unknown action", status_code=404)

        app = App.query.filter(App.name == app).first()
        if app is None:
            return self.respond("Invalid app", status_code=404)

        try:
            return hook.deploy(app, env)
        except NotImplementedError:
            return self.respond(status_code=404) 
開發者ID:getsentry,項目名稱:freight,代碼行數:27,代碼來源:webhooks.py

示例8: is_authorized

# 需要導入模塊: import hmac [as 別名]
# 或者: from hmac import compare_digest [as 別名]
def is_authorized(self):
        current_user = get_current_user()
        if current_user:
            return True

        try:
            auth = request.headers["Authorization"]
        except KeyError:
            return False

        try:
            method, payload = auth.split(" ", 1)
        except ValueError:
            return False

        if method != "Key":
            return False

        if not compare_digest(payload, current_app.config["API_KEY"]):
            return False

        return True 
開發者ID:getsentry,項目名稱:freight,代碼行數:24,代碼來源:base.py

示例9: test_generate_api_token

# 需要導入模塊: import hmac [as 別名]
# 或者: from hmac import compare_digest [as 別名]
def test_generate_api_token(self):
        token = self.profile.generate_api_token()

        self.assertIsInstance(token, str)
        self.assertIsInstance(self.profile.api_token, str)

        user_id, raw_token = struct.unpack('>I32s', base64.urlsafe_b64decode(token))

        self.assertEqual(self.users['normal'].id, user_id)
        self.assertEqual(len(raw_token), 32)

        self.assertTrue(
            hmac.compare_digest(
                hmac.new(force_bytes(settings.SECRET_KEY), msg=force_bytes(raw_token), digestmod='sha256').hexdigest(),
                self.profile.api_token,
            ),
        ) 
開發者ID:DMOJ,項目名稱:online-judge,代碼行數:19,代碼來源:test_profile.py

示例10: key_valid_const

# 需要導入模塊: import hmac [as 別名]
# 或者: from hmac import compare_digest [as 別名]
def key_valid_const(app_id: int, token: str, origin: Origin) -> bool:
    """Constant time check to see if `token` exists in the database. Compares
    against all keys even if a match is found. Validates against the app id
    and the hardware id provided."""
    current_app.logger.info(f"key lookup by token {token} from {origin}")
    found = False
    for key in Key.query.all():
        if (compare_digest(token, key.token) and
                key.enabled and key.app_id == app_id
                and compare_digest(origin.hwid, key.hwid)):

            found = True
            key.last_check_ts = datetime.utcnow()
            key.last_check_ip = origin.ip
            key.total_checks += 1
            AuditLog.from_key(key, f"key check from {origin}", Event.KeyAccess)
    return found 
開發者ID:usrbinsam,項目名稱:mini-key-server,代碼行數:19,代碼來源:keymanager.py

示例11: verify_source_is_github

# 需要導入模塊: import hmac [as 別名]
# 或者: from hmac import compare_digest [as 別名]
def verify_source_is_github(data, headers):
    if USE_GITHUB_SECRET:
        if data is None:
            return False, {"statusCode": 400, "body": "Request body must contain json"}

        digest = _get_digest(GITHUB_SECRET, data)
        if digest is not None:
            header_signature = headers.get("X-Hub-Signature")
            sig_parts = header_signature.split('=', 1)

            if not isinstance(digest, str):
                digest = str(digest)

            if len(sig_parts) < 2 or sig_parts[0] != 'sha1' or not hmac.compare_digest(sig_parts[1], digest):
                return False, {"statusCode": 400, "body": "Invalid Signature"}

    # Implement ping
    event = headers.get('X-GitHub-Event', 'ping')
    if event == 'ping':
        return False, {"statusCode": 200, "body": {'msg': 'pong'}}

    return True, {} 
開發者ID:alvarocavalcanti,項目名稱:pierre-decheck,代碼行數:24,代碼來源:pierre.py

示例12: app_switch

# 需要導入模塊: import hmac [as 別名]
# 或者: from hmac import compare_digest [as 別名]
def app_switch():
    if switch.config.http.is_secure:
        secret = request.headers.get("X-Secret")
        if secret is None \
           or not hmac.compare_digest(switch.config.http.secret, secret):
            flask.abort(403)

    cases = {
        "host": switch.switch_to_host,
        "guest": switch.switch_to_guest
    }

    if not request.json \
       or not "to" in request.json \
       or not request.json["to"] in cases:
        flask.abort(400)

    error = None
    try:
        cases[request.json["to"]]()
    except:
        error = traceback.format_exc()

    return flask.jsonify({"success": True, "error": error}) 
開發者ID:alexbakker,項目名稱:virtkvm,代碼行數:26,代碼來源:__init__.py

示例13: verify_signature

# 需要導入模塊: import hmac [as 別名]
# 或者: from hmac import compare_digest [as 別名]
def verify_signature(request):
    timestamp = request.headers.get('X-Slack-Request-Timestamp', '')
    signature = request.headers.get('X-Slack-Signature', '')

    req = str.encode('v0:{}:'.format(timestamp)) + request.get_data()
    request_digest = hmac.new(
        str.encode(os.environ['SLACK_SECRET']),
        req, hashlib.sha256
    ).hexdigest()
    request_hash = 'v0={}'.format(request_digest)

    if not hmac.compare_digest(request_hash, signature):
        raise ValueError('Invalid request/credentials.')
# [END functions_verify_webhook]


# [START functions_slack_format] 
開發者ID:GoogleCloudPlatform,項目名稱:python-docs-samples,代碼行數:19,代碼來源:main.py

示例14: is_a_valid_mailgun_post

# 需要導入模塊: import hmac [as 別名]
# 或者: from hmac import compare_digest [as 別名]
def is_a_valid_mailgun_post(request):
    """
    Taken from
        http://mailgun-documentation.readthedocs.io/en/latest/
            user_manual.html#webhooks
    :param request: Request object
    :return: True or False if the request was signed by mailgun
    """
    token = request.POST['token']
    timestamp = request.POST['timestamp']
    signature = request.POST['signature']
    key = getattr(settings, 'MAILGUN_PRIVATE_API_KEY', '').encode('utf-8')
    msg = ('{}{}'.format(timestamp, token)).encode('utf-8')
    hmac_digest = hmac.new(key=key, msg=msg, digestmod=hashlib.sha256
                           ).hexdigest()
    return hmac.compare_digest(signature, hmac_digest) 
開發者ID:codeforamerica,項目名稱:intake,代碼行數:18,代碼來源:mailgun_api_service.py

示例15: verify_csrf

# 需要導入模塊: import hmac [as 別名]
# 或者: from hmac import compare_digest [as 別名]
def verify_csrf(
    session_token_name=_QUAY_CSRF_TOKEN_NAME,
    request_token_name=_QUAY_CSRF_TOKEN_NAME,
    check_header=True,
):
    """
    Verifies that the CSRF token with the given name is found in the session and that the matching
    token is found in the request args or values.
    """
    token = str(session.get(session_token_name, ""))
    found_token = str(request.values.get(request_token_name, ""))
    if check_header and not found_token:
        found_token = str(request.headers.get(_QUAY_CSRF_HEADER_NAME, ""))

    if not token or not found_token or not hmac.compare_digest(token, found_token):
        msg = "CSRF Failure. Session token (%s) was %s and request token (%s) was %s"
        logger.error(msg, session_token_name, token, request_token_name, found_token)
        abort(403, message="CSRF token was invalid or missing.") 
開發者ID:quay,項目名稱:quay,代碼行數:20,代碼來源:csrf.py


注:本文中的hmac.compare_digest方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。