Python django.utils.crypto.constant_time_compare() Examples
The following are 30
code examples of django.utils.crypto.constant_time_compare().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
django.utils.crypto
, or try the search function
.
Example #1
Source File: cookie.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
def _decode(self, data): """ Safely decodes an encoded text stream back into a list of messages. If the encoded text stream contained an invalid hash or was in an invalid format, ``None`` is returned. """ if not data: return None bits = data.split('$', 1) if len(bits) == 2: hash, value = bits if constant_time_compare(hash, self._hash(value)): try: # If we get here (and the JSON decode works), everything is # good. In any other case, drop back and return None. return json.loads(value, cls=MessageDecoder) except ValueError: pass # Mark the data as used (so it gets removed) since something was wrong # with the data. self.used = True return None
Example #2
Source File: cookie.py From openhgsenti with Apache License 2.0 | 6 votes |
def _decode(self, data): """ Safely decodes an encoded text stream back into a list of messages. If the encoded text stream contained an invalid hash or was in an invalid format, ``None`` is returned. """ if not data: return None bits = data.split('$', 1) if len(bits) == 2: hash, value = bits if constant_time_compare(hash, self._hash(value)): try: # If we get here (and the JSON decode works), everything is # good. In any other case, drop back and return None. return json.loads(value, cls=MessageDecoder) except ValueError: pass # Mark the data as used (so it gets removed) since something was wrong # with the data. self.used = True return None
Example #3
Source File: tokens.py From openhgsenti with Apache License 2.0 | 6 votes |
def check_token(self, user, token): """ Check that a password reset token is correct for a given user. """ # Parse the token try: ts_b36, hash = token.split("-") except ValueError: return False try: ts = base36_to_int(ts_b36) except ValueError: return False # Check that the timestamp/uid has not been tampered with if not constant_time_compare(self._make_token_with_timestamp(user, ts), token): return False # Check the timestamp is within limit if (self._num_days(self._today()) - ts) > settings.PASSWORD_RESET_TIMEOUT_DAYS: return False return True
Example #4
Source File: cookie.py From Hands-On-Application-Development-with-PyCharm with MIT License | 6 votes |
def _decode(self, data): """ Safely decode an encoded text stream back into a list of messages. If the encoded text stream contained an invalid hash or was in an invalid format, return None. """ if not data: return None bits = data.split('$', 1) if len(bits) == 2: hash, value = bits if constant_time_compare(hash, self._hash(value)): try: # If we get here (and the JSON decode works), everything is # good. In any other case, drop back and return None. return json.loads(value, cls=MessageDecoder) except json.JSONDecodeError: pass # Mark the data as used (so it gets removed) since something was wrong # with the data. self.used = True return None
Example #5
Source File: cookie.py From python2017 with MIT License | 6 votes |
def _decode(self, data): """ Safely decodes an encoded text stream back into a list of messages. If the encoded text stream contained an invalid hash or was in an invalid format, ``None`` is returned. """ if not data: return None bits = data.split('$', 1) if len(bits) == 2: hash, value = bits if constant_time_compare(hash, self._hash(value)): try: # If we get here (and the JSON decode works), everything is # good. In any other case, drop back and return None. return json.loads(value, cls=MessageDecoder) except ValueError: pass # Mark the data as used (so it gets removed) since something was wrong # with the data. self.used = True return None
Example #6
Source File: video_calls.py From zulip with Apache License 2.0 | 6 votes |
def complete_zoom_user_in_realm( request: HttpRequest, code: str = REQ(), state: Dict[str, str] = REQ(validator=check_dict([("sid", check_string)], value_validator=check_string)), ) -> HttpResponse: if not constant_time_compare(state["sid"], get_zoom_sid(request)): raise JsonableError(_("Invalid Zoom session identifier")) oauth = get_zoom_session(request.user) try: token = oauth.fetch_token( "https://zoom.us/oauth/token", code=code, client_secret=settings.VIDEO_ZOOM_CLIENT_SECRET, ) except OAuth2Error: raise JsonableError(_("Invalid Zoom credentials")) do_set_zoom_token(request.user, token) return render(request, "zerver/close_window.html")
Example #7
Source File: tokens.py From fomalhaut-panel with MIT License | 6 votes |
def check_token(self, user, token): """ Check that a password reset token is correct for a given user. """ # Parse the token try: ts_b36, hash = token.split("-") except ValueError: return False try: ts = base36_to_int(ts_b36) except ValueError: return False # Check that the timestamp/uid has not been tampered with if not constant_time_compare(self._make_token_with_timestamp(user, ts), token): return False # Check the timestamp is within limit if (self._num_days(self._today()) - ts) > settings.PASSWORD_RESET_TIMEOUT_DAYS: return False return True
Example #8
Source File: utils.py From django-users2 with BSD 3-Clause "New" or "Revised" License | 6 votes |
def check_token(self, user, token): """ Check that a activation token is correct for a given user. """ # Parse the token try: ts_b36, hash = token.split('-') except ValueError: return False try: ts = base36_to_int(ts_b36) except ValueError: return False # Check that the timestamp/uid has not been tampered with if not constant_time_compare(self._make_token_with_timestamp(user, ts), token): return False # Check the timestamp is within limit if (self._num_days(self._today()) - ts) > settings.USERS_EMAIL_CONFIRMATION_TIMEOUT_DAYS: return False return True
Example #9
Source File: cookie.py From bioforum with MIT License | 6 votes |
def _decode(self, data): """ Safely decode an encoded text stream back into a list of messages. If the encoded text stream contained an invalid hash or was in an invalid format, return None. """ if not data: return None bits = data.split('$', 1) if len(bits) == 2: hash, value = bits if constant_time_compare(hash, self._hash(value)): try: # If we get here (and the JSON decode works), everything is # good. In any other case, drop back and return None. return json.loads(value, cls=MessageDecoder) except ValueError: pass # Mark the data as used (so it gets removed) since something was wrong # with the data. self.used = True return None
Example #10
Source File: verification.py From django-rest-registration with MIT License | 6 votes |
def verify(self): data = self._data signature = data.get(self.SIGNATURE_FIELD, None) if signature is None: raise BadSignature() expected_signature = self.calculate_signature() if not constant_time_compare(signature, expected_signature): raise BadSignature() valid_period = self.get_valid_period() if self.USE_TIMESTAMP and valid_period is not None: timestamp = data[self.TIMESTAMP_FIELD] timestamp = int(timestamp) current_timestamp = get_current_timestamp() valid_period_secs = valid_period.total_seconds() if current_timestamp - timestamp > valid_period_secs: raise SignatureExpired()
Example #11
Source File: tokens.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
def check_token(self, user, token): """ Check that a password reset token is correct for a given user. """ # Parse the token try: ts_b36, hash = token.split("-") except ValueError: return False try: ts = base36_to_int(ts_b36) except ValueError: return False # Check that the timestamp/uid has not been tampered with if not constant_time_compare(self._make_token_with_timestamp(user, ts), token): return False # Check the timestamp is within limit if (self._num_days(self._today()) - ts) > settings.PASSWORD_RESET_TIMEOUT_DAYS: return False return True
Example #12
Source File: retro.py From jorvik with GNU General Public License v3.0 | 5 votes |
def verify(self, password, encoded): algorithm, iterations, salt, hash = encoded.split('$', 3) assert algorithm == self.algorithm encoded_2 = self.encode(password, '') return constant_time_compare(encoded, encoded_2)
Example #13
Source File: signing.py From luscan-devel with GNU General Public License v2.0 | 5 votes |
def unsign(self, signed_value): signed_value = force_str(signed_value) if not self.sep in signed_value: raise BadSignature('No "%s" found in value' % self.sep) value, sig = signed_value.rsplit(self.sep, 1) if constant_time_compare(sig, self.signature(value)): return force_text(value) raise BadSignature('Signature "%s" does not match' % sig)
Example #14
Source File: base.py From wechat-python-sdk with BSD 2-Clause "Simplified" License | 5 votes |
def decode(self, context_data): encoded_data = base64.b64decode(force_bytes(context_data)) try: hash, serialized = encoded_data.split(b':', 1) expected_hash = self._hash(serialized) if not constant_time_compare(hash.decode(), expected_hash): raise SuspiciousOpenID('Context data corrupted') else: return self.serializer().loads(serialized) except Exception as e: # TODO: logger return {}
Example #15
Source File: hash.py From eoj3 with MIT License | 5 votes |
def check_token(self, user, token, expire_minutes=-1): try: (timestamp, content_type_id, object_id, _) = token.split("-") timestamp = base36_to_int(timestamp) content_type_id = base36_to_int(content_type_id) object_id = base36_to_int(object_id) except ValueError: return None if not constant_time_compare(self._make_hash(user, timestamp, content_type_id, object_id), token): return None if self._num_minutes() - timestamp > expire_minutes > 0: return None return ContentType.objects.get_for_id(content_type_id).get_object_for_this_type(pk=object_id)
Example #16
Source File: __init__.py From openhgsenti with Apache License 2.0 | 5 votes |
def get_user(request): """ Returns the user model instance associated with the given request session. If no user is retrieved an instance of `AnonymousUser` is returned. """ from .models import AnonymousUser user = None try: user_id = _get_user_session_key(request) backend_path = request.session[BACKEND_SESSION_KEY] except KeyError: pass else: if backend_path in settings.AUTHENTICATION_BACKENDS: backend = load_backend(backend_path) user = backend.get_user(user_id) # Verify the session if ('django.contrib.auth.middleware.SessionAuthenticationMiddleware' in settings.MIDDLEWARE_CLASSES and hasattr(user, 'get_session_auth_hash')): session_hash = request.session.get(HASH_SESSION_KEY) session_hash_verified = session_hash and constant_time_compare( session_hash, user.get_session_auth_hash() ) if not session_hash_verified: request.session.flush() user = None return user or AnonymousUser()
Example #17
Source File: models.py From c3nav with Apache License 2.0 | 5 votes |
def verify(self): # noinspection PyUnresolvedReferences return constant_time_compare( self.session_auth_hash, self.user.get_session_auth_hash() )
Example #18
Source File: csrf.py From python2017 with MIT License | 5 votes |
def _compare_salted_tokens(request_csrf_token, csrf_token): # Assume both arguments are sanitized -- that is, strings of # length CSRF_TOKEN_LENGTH, all CSRF_ALLOWED_CHARS. return constant_time_compare( _unsalt_cipher_token(request_csrf_token), _unsalt_cipher_token(csrf_token), )
Example #19
Source File: test_crypto.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_constant_time_compare(self): # It's hard to test for constant time, just test the result. self.assertTrue(constant_time_compare(b'spam', b'spam')) self.assertFalse(constant_time_compare(b'spam', b'eggs')) self.assertTrue(constant_time_compare('spam', 'spam')) self.assertFalse(constant_time_compare('spam', 'eggs'))
Example #20
Source File: __init__.py From python2017 with MIT License | 5 votes |
def get_user(request): """ Returns the user model instance associated with the given request session. If no user is retrieved an instance of `AnonymousUser` is returned. """ from .models import AnonymousUser user = None try: user_id = _get_user_session_key(request) backend_path = request.session[BACKEND_SESSION_KEY] except KeyError: pass else: if backend_path in settings.AUTHENTICATION_BACKENDS: backend = load_backend(backend_path) user = backend.get_user(user_id) # Verify the session if hasattr(user, 'get_session_auth_hash'): session_hash = request.session.get(HASH_SESSION_KEY) session_hash_verified = session_hash and constant_time_compare( session_hash, user.get_session_auth_hash() ) if not session_hash_verified: request.session.flush() user = None return user or AnonymousUser()
Example #21
Source File: hashers.py From ika with GNU Affero General Public License v3.0 | 5 votes |
def verify(self, password, encoded): md5_crypt = self._load_library().md5_crypt algorithm, salt, data = encoded.split('$', 2) assert algorithm == self.algorithm return constant_time_compare(data, md5_crypt.hash(force_str(password), salt=salt).split('$')[-1])
Example #22
Source File: tokens.py From python2017 with MIT License | 5 votes |
def check_token(self, user, token): """ Check that a password reset token is correct for a given user. """ if not (user and token): return False # Parse the token try: ts_b36, hash = token.split("-") except ValueError: return False try: ts = base36_to_int(ts_b36) except ValueError: return False # Check that the timestamp/uid has not been tampered with if not constant_time_compare(self._make_token_with_timestamp(user, ts), token): return False # Check the timestamp is within limit if (self._num_days(self._today()) - ts) > settings.PASSWORD_RESET_TIMEOUT_DAYS: return False return True
Example #23
Source File: test_crypto.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_constant_time_compare(self): # It's hard to test for constant time, just test the result. self.assertTrue(constant_time_compare(b'spam', b'spam')) self.assertFalse(constant_time_compare(b'spam', b'eggs')) self.assertTrue(constant_time_compare('spam', 'spam')) self.assertFalse(constant_time_compare('spam', 'eggs'))
Example #24
Source File: basicauthutils.py From django-basicauth with MIT License | 5 votes |
def validate_request(request): """Check an incoming request. Returns: - True if authentication passed - Adding request['REMOTE_USER'] as authenticated username. """ if getattr(settings, 'BASICAUTH_DISABLE', False): # Not to use this env return True if 'HTTP_AUTHORIZATION' not in request.META: return False authorization_header = request.META['HTTP_AUTHORIZATION'] ret = extract_basicauth(authorization_header) if not ret: return False username, password = ret raw_pass = settings.BASICAUTH_USERS.get(username) if raw_pass is None: return False # To avoid timing atacks # https://security.stackexchange.com/questions/83660/simple-string-comparisons-not-secure-against-timing-attacks if not constant_time_compare(raw_pass, password): return False request.META['REMOTE_USER'] = username return True
Example #25
Source File: auth.py From django-pgschemas with MIT License | 5 votes |
def get_user(scope): """ Return the user model instance associated with the given scope. If no user is retrieved, return an instance of `AnonymousUser`. """ if "session" not in scope: raise ValueError("Cannot find session in scope. You should wrap your consumer in SessionMiddleware.") user = None session = scope["session"] with scope["tenant"]: try: user_id = _get_user_session_key(session) backend_path = session[BACKEND_SESSION_KEY] except KeyError: pass else: if backend_path in settings.AUTHENTICATION_BACKENDS: backend = load_backend(backend_path) user = backend.get_user(user_id) # Verify the session if hasattr(user, "get_session_auth_hash"): session_hash = session.get(HASH_SESSION_KEY) session_hash_verified = session_hash and constant_time_compare( session_hash, user.get_session_auth_hash() ) if not session_hash_verified: session.flush() user = None return user or AnonymousUser()
Example #26
Source File: views.py From mangaki with GNU Affero General Public License v3.0 | 5 votes |
def update_settings(request): is_ok = None if request.method == 'POST': # Confirmed from mail link is_ok = 'yes' in request.POST username = request.POST.get('username') token = request.POST.get('token') elif request.method == 'GET': # Clicked on mail link username = request.GET.get('username') token = request.GET.get('token') expected_token = compute_token(NEWS_SALT, username) if not constant_time_compare(token, expected_token): # If the token is invalid, add an error message messages.error(request, 'Vous n\'êtes pas autorisé à effectuer cette action.') return render(request, 'settings.html', status=401) # Unauthorized elif is_ok is not None: message = 'Votre profil a bien été mis à jour. ' if is_ok: message += 'Profitez bien de Mangaki !' else: message += 'Vous ne recevrez plus de mails de notre part.' Profile.objects.filter( user__username=username).update(newsletter_ok=is_ok) messages.success(request, message) return render(request, 'settings.html') return render(request, 'settings.html', {'username': username, 'token': token})
Example #27
Source File: __init__.py From GTDWeb with GNU General Public License v2.0 | 5 votes |
def get_user(request): """ Returns the user model instance associated with the given request session. If no user is retrieved an instance of `AnonymousUser` is returned. """ from .models import AnonymousUser user = None try: user_id = _get_user_session_key(request) backend_path = request.session[BACKEND_SESSION_KEY] except KeyError: pass else: if backend_path in settings.AUTHENTICATION_BACKENDS: backend = load_backend(backend_path) user = backend.get_user(user_id) # Verify the session if ('django.contrib.auth.middleware.SessionAuthenticationMiddleware' in settings.MIDDLEWARE_CLASSES and hasattr(user, 'get_session_auth_hash')): session_hash = request.session.get(HASH_SESSION_KEY) session_hash_verified = session_hash and constant_time_compare( session_hash, user.get_session_auth_hash() ) if not session_hash_verified: request.session.flush() user = None return user or AnonymousUser()
Example #28
Source File: signing.py From GTDWeb with GNU General Public License v2.0 | 5 votes |
def unsign(self, signed_value): signed_value = force_str(signed_value) if self.sep not in signed_value: raise BadSignature('No "%s" found in value' % self.sep) value, sig = signed_value.rsplit(self.sep, 1) if constant_time_compare(sig, self.signature(value)): return force_text(value) raise BadSignature('Signature "%s" does not match' % sig)
Example #29
Source File: csrf.py From bioforum with MIT License | 5 votes |
def _compare_salted_tokens(request_csrf_token, csrf_token): # Assume both arguments are sanitized -- that is, strings of # length CSRF_TOKEN_LENGTH, all CSRF_ALLOWED_CHARS. return constant_time_compare( _unsalt_cipher_token(request_csrf_token), _unsalt_cipher_token(csrf_token), )
Example #30
Source File: __init__.py From bioforum with MIT License | 5 votes |
def get_user(request): """ Return the user model instance associated with the given request session. If no user is retrieved, return an instance of `AnonymousUser`. """ from .models import AnonymousUser user = None try: user_id = _get_user_session_key(request) backend_path = request.session[BACKEND_SESSION_KEY] except KeyError: pass else: if backend_path in settings.AUTHENTICATION_BACKENDS: backend = load_backend(backend_path) user = backend.get_user(user_id) # Verify the session if hasattr(user, 'get_session_auth_hash'): session_hash = request.session.get(HASH_SESSION_KEY) session_hash_verified = session_hash and constant_time_compare( session_hash, user.get_session_auth_hash() ) if not session_hash_verified: request.session.flush() user = None return user or AnonymousUser()