django.utils.crypto.constant_time_compare

Here are the examples of the python api django.utils.crypto.constant_time_compare taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

200 Examples 7

Example 1

Project: GAE-Bulk-Mailer
Source File: signing.py
View license
    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 2

Project: django-bcrypt
Source File: models.py
View license
def check_password(raw_password, enc_password):
    if enc_password[0] == '$':
        algo = enc_password[1:].split('$', 1)[0]
        assert algo in ('2a', '2', 'bcrypt')

        return constant_time_compare(
            enc_password,
            bcrypt.hashpw(smart_str(raw_password), enc_password),
        )

    return django_check_password(raw_password, enc_password)

Example 3

Project: PyClassLessons
Source File: forms.py
View license
    def clean_security_hash(self):
        """Check the security hash."""
        security_hash_dict = {
            'content_type' : self.data.get("content_type", ""),
            'object_pk' : self.data.get("object_pk", ""),
            'timestamp' : self.data.get("timestamp", ""),
        }
        expected_hash = self.generate_security_hash(**security_hash_dict)
        actual_hash = self.cleaned_data["security_hash"]
        if not constant_time_compare(expected_hash, actual_hash):
            raise forms.ValidationError("Security hash check failed.")
        return actual_hash

Example 4

Project: PyClassLessons
Source File: base.py
View license
    def decode(self, session_data):
        encoded_data = base64.b64decode(force_bytes(session_data))
        try:
            # could produce ValueError if there is no ':'
            hash, serialized = encoded_data.split(b':', 1)
            expected_hash = self._hash(serialized)
            if not constant_time_compare(hash.decode(), expected_hash):
                raise SuspiciousSession("Session data corrupted")
            else:
                return self.serializer().loads(serialized)
        except Exception as e:
            # ValueError, SuspiciousOperation, unpickling exceptions. If any of
            # these happen, just return an empty dictionary (an empty session).
            if isinstance(e, SuspiciousOperation):
                logger = logging.getLogger('django.security.%s' %
                        e.__class__.__name__)
                logger.warning(force_text(e))
            return {}

Example 5

Project: PyClassLessons
Source File: signing.py
View license
    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 6

Project: Django--an-app-at-a-time
Source File: base.py
View license
    def decode(self, session_data):
        encoded_data = base64.b64decode(force_bytes(session_data))
        try:
            # could produce ValueError if there is no ':'
            hash, serialized = encoded_data.split(b':', 1)
            expected_hash = self._hash(serialized)
            if not constant_time_compare(hash.decode(), expected_hash):
                raise SuspiciousSession("Session data corrupted")
            else:
                return self.serializer().loads(serialized)
        except Exception as e:
            # ValueError, SuspiciousOperation, unpickling exceptions. If any of
            # these happen, just return an empty dictionary (an empty session).
            if isinstance(e, SuspiciousOperation):
                logger = logging.getLogger('django.security.%s' %
                        e.__class__.__name__)
                logger.warning(force_text(e))
            return {}

Example 7

Project: Django--an-app-at-a-time
Source File: signing.py
View license
    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 8

Project: django-primate
Source File: helpers.py
View license
def check_password(raw_password, enc_password):
    """
    Returns a boolean of whether the raw_password was correct. Handles
    encryption formats behind the scenes.
    """
    algo, salt, hsh = enc_password.split('$')
    return constant_time_compare(hsh, get_hexdigest(algo, salt, raw_password))

Example 9

Project: splunk-webframework
Source File: forms.py
View license
    def clean_security_hash(self):
        """Check the security hash."""
        security_hash_dict = {
            'content_type' : self.data.get("content_type", ""),
            'object_pk' : self.data.get("object_pk", ""),
            'timestamp' : self.data.get("timestamp", ""),
        }
        expected_hash = self.generate_security_hash(**security_hash_dict)
        actual_hash = self.cleaned_data["security_hash"]
        if not constant_time_compare(expected_hash, actual_hash):
            raise forms.ValidationError("Security hash check failed.")
        return actual_hash

Example 10

Project: splunk-webframework
Source File: base.py
View license
    def decode(self, session_data):
        encoded_data = base64.b64decode(force_bytes(session_data))
        try:
            # could produce ValueError if there is no ':'
            hash, serialized = encoded_data.split(b':', 1)
            expected_hash = self._hash(serialized)
            if not constant_time_compare(hash.decode(), expected_hash):
                raise SuspiciousOperation("Session data corrupted")
            else:
                return self.serializer().loads(serialized)
        except Exception:
            # ValueError, SuspiciousOperation, deserialization exceptions. If
            # any of these happen, just return an empty dictionary (an empty
            # session).
            return {}

Example 11

Project: splunk-webframework
Source File: signing.py
View license
    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 12

Project: froide
Source File: models.py
View license
    def check_and_unfollow(self, check):
        secret = self.get_follow_secret()
        if constant_time_compare(check, secret):
            self.delete()
            return True
        return False

Example 13

Project: python-useful
Source File: concurrency.py
View license
def _validate_object_version(datadict):
    form_pk, form_hash = None, None
    form_version = datadict.get('object_version', '')
    if form_version:
        try:
            form_pk, form_hash, form_hmac = form_version.split('-', 2)
            if not form_pk or not form_hash or not form_hmac:
                raise ValueError
        except ValueError:
            raise forms.ValidationError("Bad object_version format.")

        if not constant_time_compare(form_hmac, _gen_hmac(form_pk, form_hash)):
            raise forms.ValidationError(_("Version protection tampered."))

    return form_pk, form_hash

Example 14

Project: cgstudiomap
Source File: base.py
View license
    def decode(self, session_data):
        encoded_data = base64.b64decode(force_bytes(session_data))
        try:
            # could produce ValueError if there is no ':'
            hash, serialized = encoded_data.split(b':', 1)
            expected_hash = self._hash(serialized)
            if not constant_time_compare(hash.decode(), expected_hash):
                raise SuspiciousSession("Session data corrupted")
            else:
                return self.serializer().loads(serialized)
        except Exception as e:
            # ValueError, SuspiciousOperation, unpickling exceptions. If any of
            # these happen, just return an empty dictionary (an empty session).
            if isinstance(e, SuspiciousOperation):
                logger = logging.getLogger('django.security.%s' %
                        e.__class__.__name__)
                logger.warning(force_text(e))
            return {}

Example 15

Project: cgstudiomap
Source File: signing.py
View license
    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 16

Project: django-nonrel
Source File: models.py
View license
def check_password(raw_password, enc_password):
    """
    Returns a boolean of whether the raw_password was correct. Handles
    encryption formats behind the scenes.
    """
    algo, salt, hsh = enc_password.split('$')
    return constant_time_compare(hsh, get_hexdigest(algo, salt, raw_password))

Example 17

Project: django-nonrel
Source File: forms.py
View license
    def clean_security_hash(self):
        """Check the security hash."""
        security_hash_dict = {
            'content_type' : self.data.get("content_type", ""),
            'object_pk' : self.data.get("object_pk", ""),
            'timestamp' : self.data.get("timestamp", ""),
        }
        expected_hash = self.generate_security_hash(**security_hash_dict)
        actual_hash = self.cleaned_data["security_hash"]
        if not constant_time_compare(expected_hash, actual_hash):
            # Fallback to Django 1.2 method for compatibility
            # PendingDeprecationWarning <- here to remind us to remove this
            # fallback in Django 1.5
            expected_hash_old = self._generate_security_hash_old(**security_hash_dict)
            if not constant_time_compare(expected_hash_old, actual_hash):
                raise forms.ValidationError("Security hash check failed.")
        return actual_hash

Example 18

Project: django-nonrel
Source File: base.py
View license
    def _decode_old(self, session_data):
        encoded_data = base64.decodestring(session_data)
        pickled, tamper_check = encoded_data[:-32], encoded_data[-32:]
        if not constant_time_compare(md5_constructor(pickled + settings.SECRET_KEY).hexdigest(),
                                     tamper_check):
            raise SuspiciousOperation("User tampered with session cookie.")
        return pickle.loads(pickled)

Example 19

Project: hue
Source File: forms.py
View license
    def clean_security_hash(self):
        """Check the security hash."""
        security_hash_dict = {
            'content_type' : self.data.get("content_type", ""),
            'object_pk' : self.data.get("object_pk", ""),
            'timestamp' : self.data.get("timestamp", ""),
        }
        expected_hash = self.generate_security_hash(**security_hash_dict)
        actual_hash = self.cleaned_data["security_hash"]
        if not constant_time_compare(expected_hash, actual_hash):
            raise forms.ValidationError("Security hash check failed.")
        return actual_hash

Example 20

Project: hue
Source File: base.py
View license
    def decode(self, session_data):
        encoded_data = base64.b64decode(force_bytes(session_data))
        try:
            # could produce ValueError if there is no ':'
            hash, serialized = encoded_data.split(b':', 1)
            expected_hash = self._hash(serialized)
            if not constant_time_compare(hash.decode(), expected_hash):
                raise SuspiciousSession("Session data corrupted")
            else:
                return self.serializer().loads(serialized)
        except Exception as e:
            # ValueError, SuspiciousOperation, unpickling exceptions. If any of
            # these happen, just return an empty dictionary (an empty session).
            if isinstance(e, SuspiciousOperation):
                logger = logging.getLogger('django.security.%s' %
                        e.__class__.__name__)
                logger.warning(force_text(e))
            return {}

Example 21

Project: hue
Source File: signing.py
View license
    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 22

Project: decode-Django
Source File: forms.py
View license
    def clean_security_hash(self):
        """Check the security hash."""
        security_hash_dict = {
            'content_type' : self.data.get("content_type", ""),
            'object_pk' : self.data.get("object_pk", ""),
            'timestamp' : self.data.get("timestamp", ""),
        }
        expected_hash = self.generate_security_hash(**security_hash_dict)
        actual_hash = self.cleaned_data["security_hash"]
        if not constant_time_compare(expected_hash, actual_hash):
            raise forms.ValidationError("Security hash check failed.")
        return actual_hash

Example 23

Project: decode-Django
Source File: base.py
View license
    def decode(self, session_data):
        encoded_data = base64.b64decode(force_bytes(session_data))
        try:
            # could produce ValueError if there is no ':'
            hash, pickled = encoded_data.split(b':', 1)
            expected_hash = self._hash(pickled)
            if not constant_time_compare(hash.decode(), expected_hash):
                raise SuspiciousOperation("Session data corrupted")
            else:
                return pickle.loads(pickled)
        except Exception:
            # ValueError, SuspiciousOperation, unpickling exceptions. If any of
            # these happen, just return an empty dictionary (an empty session).
            return {}

Example 24

Project: decode-Django
Source File: signing.py
View license
    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 25

Project: django
Source File: base.py
View license
    def decode(self, session_data):
        encoded_data = base64.b64decode(force_bytes(session_data))
        try:
            # could produce ValueError if there is no ':'
            hash, serialized = encoded_data.split(b':', 1)
            expected_hash = self._hash(serialized)
            if not constant_time_compare(hash.decode(), expected_hash):
                raise SuspiciousSession("Session data corrupted")
            else:
                return self.serializer().loads(serialized)
        except Exception as e:
            # ValueError, SuspiciousOperation, unpickling exceptions. If any of
            # these happen, just return an empty dictionary (an empty session).
            if isinstance(e, SuspiciousOperation):
                logger = logging.getLogger('django.security.%s' % e.__class__.__name__)
                logger.warning(force_text(e))
            return {}

Example 26

Project: django
Source File: signing.py
View license
    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 27

Project: django
Source File: csrf.py
View license
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 28

Project: django-contrib-comments
Source File: forms.py
View license
    def clean_security_hash(self):
        """Check the security hash."""
        security_hash_dict = {
            'content_type': self.data.get("content_type", ""),
            'object_pk': self.data.get("object_pk", ""),
            'timestamp': self.data.get("timestamp", ""),
        }
        expected_hash = self.generate_security_hash(**security_hash_dict)
        actual_hash = self.cleaned_data["security_hash"]
        if not constant_time_compare(expected_hash, actual_hash):
            raise forms.ValidationError("Security hash check failed.")
        return actual_hash

Example 29

Project: wechat-python-sdk
Source File: base.py
View license
    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 30

Project: HealthStarter
Source File: base.py
View license
    def decode(self, session_data):
        encoded_data = base64.b64decode(force_bytes(session_data))
        try:
            # could produce ValueError if there is no ':'
            hash, serialized = encoded_data.split(b':', 1)
            expected_hash = self._hash(serialized)
            if not constant_time_compare(hash.decode(), expected_hash):
                raise SuspiciousSession("Session data corrupted")
            else:
                return self.serializer().loads(serialized)
        except Exception as e:
            # ValueError, SuspiciousOperation, unpickling exceptions. If any of
            # these happen, just return an empty dictionary (an empty session).
            if isinstance(e, SuspiciousOperation):
                logger = logging.getLogger('django.security.%s' %
                        e.__class__.__name__)
                logger.warning(force_text(e))
            return {}

Example 31

Project: HealthStarter
Source File: signing.py
View license
    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 32

Project: django-sha2
Source File: hashers.py
View license
    def verify(self, password, encoded):
        algo_and_hash, key_ver = encoded.rsplit('$', 1)
        try:
            shared_key = settings.HMAC_KEYS[key_ver]
        except KeyError:
            log.info('Invalid shared key version "{0}"'.format(key_ver))
            # Fall back to normal bcrypt
            algorithm, data = encoded.split('$', 1)
            return constant_time_compare(data, bcrypt.hashpw(password, data))

        bc_value = '${0}'.format(algo_and_hash.split('$', 1)[1])  # Yes, bcrypt <3s the leading $.
        hmac_value = self._hmac_create(password, shared_key)
        return bcrypt.hashpw(hmac_value, bc_value) == bc_value

Example 33

Project: muspy
Source File: tools.py
View license
def check_password(user, password):
    # Legacy users have their passwords hashed with SHA512.
    # TODO: Remove when Django supports SHA512 (1.4?)
    if user.password.startswith('sha512$'):
        import hashlib
        from django.utils.crypto import constant_time_compare
        from django.utils.encoding import smart_str
        algo, salt, hsh = user.password.split('$')
        password, salt = smart_str(password), smart_str(salt)
        hash = hashlib.new('sha512')
        hash.update(password)
        hash.update(salt)
        hexdigest = hash.hexdigest()
        return constant_time_compare(hsh, hexdigest)
    return user.check_password(password)

Example 34

Project: sentry
Source File: email.py
View license
    def unsign(self, signed_value):
        # This unsign is identical to subclass except for the lowercasing
        # See: https://github.com/django/django/blob/1.6.11/django/core/signing.py#L165-L172
        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.lower(), self.signature(value)):
            return force_text(value)
        raise BadSignature('Signature "%s" does not match' % sig)

Example 35

Project: sentry
Source File: otp.py
View license
    def verify(self, otp, ts=None, window=None, return_counter=False,
               check_counter_func=None):
        ts = _get_ts(ts)
        if window is None:
            window = self.default_window
        for i in range(-window, window + 1):
            counter = int(ts) // self.interval + i
            if constant_time_compare(otp, self.generate_otp(counter=counter)):
                # Check for blacklisted counters after the constant time
                # compare
                if check_counter_func is not None \
                   and not check_counter_func(counter):
                    continue
                if return_counter:
                    return counter
                return True
        if return_counter:
            return None
        return False

Example 36

Project: sentry
Source File: mailgun_inbound_webhook.py
View license
    def verify(self, api_key, token, timestamp, signature):
        return constant_time_compare(signature, hmac.new(
            key=api_key.encode('utf-8'),
            msg=('{}{}'.format(timestamp, token)).encode('utf-8'),
            digestmod=sha256
        ).hexdigest())

Example 37

Project: sentry
Source File: release_webhook.py
View license
    def verify(self, plugin_id, project_id, token, signature):
        return constant_time_compare(signature, hmac.new(
            key=token.encode('utf-8'),
            msg=('{}-{}'.format(plugin_id, project_id)).encode('utf-8'),
            digestmod=sha256
        ).hexdigest())

Example 38

Project: sentry
Source File: __init__.py
View license
    def validate_state(self):
        """Validate state value. Raises exception on error, returns state
        value if valid."""
        if not self.STATE_PARAMETER and not self.REDIRECT_STATE:
            return None
        state = self.request.session.get(self.AUTH_BACKEND.name + '_state')
        if state:
            request_state = (self.data.get('state') or
                             self.data.get('redirect_state'))
            if not request_state:
                raise AuthMissingParameter(self, 'state')
            elif not state:
                raise AuthStateMissing(self, 'state')
            elif not constant_time_compare(request_state, state):
                raise AuthStateForbidden(self)
        return state

Example 39

Project: golismero
Source File: signing.py
View license
    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 40

Project: feedsanitizer
Source File: forms.py
View license
    def clean_security_hash(self):
        """Check the security hash."""
        security_hash_dict = {
            'content_type' : self.data.get("content_type", ""),
            'object_pk' : self.data.get("object_pk", ""),
            'timestamp' : self.data.get("timestamp", ""),
        }
        expected_hash = self.generate_security_hash(**security_hash_dict)
        actual_hash = self.cleaned_data["security_hash"]
        if not constant_time_compare(expected_hash, actual_hash):
            # Fallback to Django 1.2 method for compatibility
            # PendingDeprecationWarning <- here to remind us to remove this
            # fallback in Django 1.5
            expected_hash_old = self._generate_security_hash_old(**security_hash_dict)
            if not constant_time_compare(expected_hash_old, actual_hash):
                raise forms.ValidationError("Security hash check failed.")
        return actual_hash

Example 41

Project: feedsanitizer
Source File: base.py
View license
    def _decode_old(self, session_data):
        encoded_data = base64.decodestring(session_data)
        pickled, tamper_check = encoded_data[:-32], encoded_data[-32:]
        if not constant_time_compare(md5_constructor(pickled + settings.SECRET_KEY).hexdigest(),
                                     tamper_check):
            raise SuspiciousOperation("User tampered with session cookie.")
        return pickle.loads(pickled)

Example 42

Project: hunch-gift-app
Source File: forms.py
View license
    def clean_security_hash(self):
        """Check the security hash."""
        security_hash_dict = {
            'content_type' : self.data.get("content_type", ""),
            'object_pk' : self.data.get("object_pk", ""),
            'timestamp' : self.data.get("timestamp", ""),
        }
        expected_hash = self.generate_security_hash(**security_hash_dict)
        actual_hash = self.cleaned_data["security_hash"]
        if not constant_time_compare(expected_hash, actual_hash):
            # Fallback to Django 1.2 method for compatibility
            # PendingDeprecationWarning <- here to remind us to remove this
            # fallback in Django 1.5
            expected_hash_old = self._generate_security_hash_old(**security_hash_dict)
            if not constant_time_compare(expected_hash_old, actual_hash):
                raise forms.ValidationError("Security hash check failed.")
        return actual_hash

Example 43

Project: hunch-gift-app
Source File: base.py
View license
    def _decode_old(self, session_data):
        encoded_data = base64.decodestring(session_data)
        pickled, tamper_check = encoded_data[:-32], encoded_data[-32:]
        if not constant_time_compare(md5_constructor(pickled + settings.SECRET_KEY).hexdigest(),
                                     tamper_check):
            raise SuspiciousOperation("User tampered with session cookie.")
        return pickle.loads(pickled)

Example 44

Project: hunch-sample-app
Source File: forms.py
View license
    def clean_security_hash(self):
        """Check the security hash."""
        security_hash_dict = {
            'content_type' : self.data.get("content_type", ""),
            'object_pk' : self.data.get("object_pk", ""),
            'timestamp' : self.data.get("timestamp", ""),
        }
        expected_hash = self.generate_security_hash(**security_hash_dict)
        actual_hash = self.cleaned_data["security_hash"]
        if not constant_time_compare(expected_hash, actual_hash):
            # Fallback to Django 1.2 method for compatibility
            # PendingDeprecationWarning <- here to remind us to remove this
            # fallback in Django 1.5
            expected_hash_old = self._generate_security_hash_old(**security_hash_dict)
            if not constant_time_compare(expected_hash_old, actual_hash):
                raise forms.ValidationError("Security hash check failed.")
        return actual_hash

Example 45

Project: hunch-sample-app
Source File: base.py
View license
    def _decode_old(self, session_data):
        encoded_data = base64.decodestring(session_data)
        pickled, tamper_check = encoded_data[:-32], encoded_data[-32:]
        if not constant_time_compare(md5_constructor(pickled + settings.SECRET_KEY).hexdigest(),
                                     tamper_check):
            raise SuspiciousOperation("User tampered with session cookie.")
        return pickle.loads(pickled)

Example 46

Project: django-formapi
Source File: api.py
View license
    def sign_ok(self, sign):
        digest = get_pairs_sign(secret=prepare_uuid_string(self.api_key.secret),
                                sorted_pairs=self.normalized_parameters())
        digest = prepare_uuid_string(digest)
        sign = prepare_uuid_string(sign)
        return constant_time_compare(sign, digest)

Example 47

Project: django-debug-toolbar
Source File: forms.py
View license
    def clean_hash(self):
        hash = self.cleaned_data['hash']

        if not constant_time_compare(hash, self.make_hash(self.data)):
            raise ValidationError('Tamper alert')

        return hash

Example 48

Project: salmon
Source File: authentication.py
View license
    def authenticate(self, request):
        has_api_key = hasattr(settings, 'API_KEY')
        using_basic_auth = 'HTTP_AUTHORIZATION' in request.META
        if using_basic_auth and has_api_key:
            auth = request.META['HTTP_AUTHORIZATION'].split()
            if len(auth) == 2 and auth[0].lower() == "basic":
                key = base64.b64decode(auth[1]).split(':')[0]
                if constant_time_compare(settings.API_KEY, key):
                    request._salmon_allowed = True
                    return (AnonymousUser, None)
                else:
                    raise exceptions.AuthenticationFailed('No such user')
        return None

Example 49

Project: salmon
Source File: authentication.py
View license
    def authenticate(self, request):
        has_api_key = hasattr(settings, 'API_KEY')
        using_basic_auth = 'HTTP_AUTHORIZATION' in request.META
        if using_basic_auth and has_api_key:
            auth = request.META['HTTP_AUTHORIZATION'].split()
            if len(auth) == 2 and auth[0].lower() == "basic":
                key = base64.b64decode(auth[1]).split(':')[0]
                if constant_time_compare(settings.API_KEY, key):
                    request._salmon_allowed = True
                    return (AnonymousUser, None)
                else:
                    raise exceptions.AuthenticationFailed('No such user')
        return None

Example 50

Project: django-anymail
Source File: mailgun.py
View license
    def validate_request(self, request):
        super(MailgunBaseWebhookView, self).validate_request(request)  # first check basic auth if enabled
        try:
            token = request.POST['token']
            timestamp = request.POST['timestamp']
            signature = str(request.POST['signature'])  # force to same type as hexdigest() (for python2)
        except KeyError:
            raise AnymailWebhookValidationFailure("Mailgun webhook called without required security fields")
        expected_signature = hmac.new(key=self.api_key, msg='{}{}'.format(timestamp, token).encode('ascii'),
                                      digestmod=hashlib.sha256).hexdigest()
        if not constant_time_compare(signature, expected_signature):
            raise AnymailWebhookValidationFailure("Mailgun webhook called with incorrect signature")