本文整理汇总了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
示例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
示例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
示例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")
示例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
示例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)
示例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)
示例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
示例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,
),
)
示例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
示例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, {}
示例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})
示例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]
示例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)
示例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.")