Python django.conf.settings.SECRET_KEY Examples

The following are 30 code examples for showing how to use django.conf.settings.SECRET_KEY(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.conf.settings , or try the search function .

Example 1
Project: coursys   Author: sfu-fas   File: photos.py    License: GNU General Public License v3.0 6 votes vote down vote up
def generate_password(input_seed):
    """
    Generate some hard-to-guess but deterministic password.
    (deterministic so we have some hope of password recovery if something gets lost)

    Note: settings.SECRET_KEY is different (and actually secret) in production.
    """
    # generate seed integer
    secret = settings.SECRET_KEY
    seed_str = '_'.join([secret, input_seed, PW_SERIES, secret])
    h = hashlib.new('sha512')
    h.update(seed_str.encode('utf8'))
    seed = int(h.hexdigest(), 16)

    # use seed to pick characters: one letter, one digit, one punctuation, length 6-10
    letter, seed = _choose_from(LETTERS, seed)
    digit, seed = _choose_from(DIGITS, seed)
    punc, seed = _choose_from(PUNCTUATION, seed)
    pw = letter + digit + punc
    for i in range(7):
        c, seed = _choose_from(ALL_CHARS, seed)
        pw += c

    return pw 
Example 2
Project: GTDWeb   Author: lanbing510   File: crypto.py    License: GNU General Public License v2.0 6 votes vote down vote up
def salted_hmac(key_salt, value, secret=None):
    """
    Returns the HMAC-SHA1 of 'value', using a key generated from key_salt and a
    secret (which defaults to settings.SECRET_KEY).

    A different key_salt should be passed in for every application of HMAC.
    """
    if secret is None:
        secret = settings.SECRET_KEY

    key_salt = force_bytes(key_salt)
    secret = force_bytes(secret)

    # We need to generate a derived key from our base key.  We can do this by
    # passing the key_salt and our base key through a pseudo-random function and
    # SHA1 works nicely.
    key = hashlib.sha1(key_salt + secret).digest()

    # If len(key_salt + secret) > sha_constructor().block_size, the above
    # line is redundant and could be replaced by key = key_salt + secret, since
    # the hmac module does the same thing for keys longer than the block size.
    # However, we need to ensure that we *always* do this.
    return hmac.new(key, msg=force_bytes(value), digestmod=hashlib.sha1) 
Example 3
Project: GTDWeb   Author: lanbing510   File: crypto.py    License: GNU General Public License v2.0 6 votes vote down vote up
def get_random_string(length=12,
                      allowed_chars='abcdefghijklmnopqrstuvwxyz'
                                    'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
    """
    Returns a securely generated random string.

    The default length of 12 with the a-z, A-Z, 0-9 character set returns
    a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
    """
    if not using_sysrandom:
        # This is ugly, and a hack, but it makes things better than
        # the alternative of predictability. This re-seeds the PRNG
        # using a value that is hard for an attacker to predict, every
        # time a random string is required. This may change the
        # properties of the chosen random sequence slightly, but this
        # is better than absolute predictability.
        random.seed(
            hashlib.sha256(
                ("%s%s%s" % (
                    random.getstate(),
                    time.time(),
                    settings.SECRET_KEY)).encode('utf-8')
            ).digest())
    return ''.join(random.choice(allowed_chars) for i in range(length)) 
Example 4
Project: aws-workshop   Author: tryolabs   File: backends.py    License: MIT License 6 votes vote down vote up
def _authenticate_credentials(self, request, token):
        """
        Try to authenticate the given credentials. If authentication is
        successful, return the user and token. If not, throw an error.
        """
        try:
            payload = jwt.decode(token, settings.SECRET_KEY)
        except:
            msg = 'Invalid authentication. Could not decode token.'
            raise exceptions.AuthenticationFailed(msg)

        try:
            user = User.objects.get(pk=payload['id'])
        except User.DoesNotExist:
            msg = 'No user matching this token was found.'
            raise exceptions.AuthenticationFailed(msg)

        if not user.is_active:
            msg = 'This user has been deactivated.'
            raise exceptions.AuthenticationFailed(msg)

        return (user, token) 
Example 5
Project: bioforum   Author: reBiocoder   File: crypto.py    License: MIT License 6 votes vote down vote up
def salted_hmac(key_salt, value, secret=None):
    """
    Return the HMAC-SHA1 of 'value', using a key generated from key_salt and a
    secret (which defaults to settings.SECRET_KEY).

    A different key_salt should be passed in for every application of HMAC.
    """
    if secret is None:
        secret = settings.SECRET_KEY

    key_salt = force_bytes(key_salt)
    secret = force_bytes(secret)

    # We need to generate a derived key from our base key.  We can do this by
    # passing the key_salt and our base key through a pseudo-random function and
    # SHA1 works nicely.
    key = hashlib.sha1(key_salt + secret).digest()

    # If len(key_salt + secret) > sha_constructor().block_size, the above
    # line is redundant and could be replaced by key = key_salt + secret, since
    # the hmac module does the same thing for keys longer than the block size.
    # However, we need to ensure that we *always* do this.
    return hmac.new(key, msg=force_bytes(value), digestmod=hashlib.sha1) 
Example 6
Project: bioforum   Author: reBiocoder   File: crypto.py    License: MIT License 6 votes vote down vote up
def get_random_string(length=12,
                      allowed_chars='abcdefghijklmnopqrstuvwxyz'
                                    'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
    """
    Return a securely generated random string.

    The default length of 12 with the a-z, A-Z, 0-9 character set returns
    a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
    """
    if not using_sysrandom:
        # This is ugly, and a hack, but it makes things better than
        # the alternative of predictability. This re-seeds the PRNG
        # using a value that is hard for an attacker to predict, every
        # time a random string is required. This may change the
        # properties of the chosen random sequence slightly, but this
        # is better than absolute predictability.
        random.seed(
            hashlib.sha256(
                ('%s%s%s' % (random.getstate(), time.time(), settings.SECRET_KEY)).encode()
            ).digest()
        )
    return ''.join(random.choice(allowed_chars) for i in range(length)) 
Example 7
Project: online-judge   Author: DMOJ   File: test_profile.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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,
            ),
        ) 
Example 8
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: crypto.py    License: MIT License 6 votes vote down vote up
def salted_hmac(key_salt, value, secret=None):
    """
    Return the HMAC-SHA1 of 'value', using a key generated from key_salt and a
    secret (which defaults to settings.SECRET_KEY).

    A different key_salt should be passed in for every application of HMAC.
    """
    if secret is None:
        secret = settings.SECRET_KEY

    key_salt = force_bytes(key_salt)
    secret = force_bytes(secret)

    # We need to generate a derived key from our base key.  We can do this by
    # passing the key_salt and our base key through a pseudo-random function and
    # SHA1 works nicely.
    key = hashlib.sha1(key_salt + secret).digest()

    # If len(key_salt + secret) > sha_constructor().block_size, the above
    # line is redundant and could be replaced by key = key_salt + secret, since
    # the hmac module does the same thing for keys longer than the block size.
    # However, we need to ensure that we *always* do this.
    return hmac.new(key, msg=force_bytes(value), digestmod=hashlib.sha1) 
Example 9
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: crypto.py    License: MIT License 6 votes vote down vote up
def get_random_string(length=12,
                      allowed_chars='abcdefghijklmnopqrstuvwxyz'
                                    'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
    """
    Return a securely generated random string.

    The default length of 12 with the a-z, A-Z, 0-9 character set returns
    a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
    """
    if not using_sysrandom:
        # This is ugly, and a hack, but it makes things better than
        # the alternative of predictability. This re-seeds the PRNG
        # using a value that is hard for an attacker to predict, every
        # time a random string is required. This may change the
        # properties of the chosen random sequence slightly, but this
        # is better than absolute predictability.
        random.seed(
            hashlib.sha256(
                ('%s%s%s' % (random.getstate(), time.time(), settings.SECRET_KEY)).encode()
            ).digest()
        )
    return ''.join(random.choice(allowed_chars) for i in range(length)) 
Example 10
Project: mrs   Author: betagouv   File: 0002_auto_adduser.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def adduser(apps, schema_editor):
    if os.getenv('CI'):
        return

    User = apps.get_model(*settings.AUTH_USER_MODEL.split('.'))

    if settings.SECRET_KEY != 'notsecret':
        return

    user, created = User.objects.get_or_create(
        username='test',
        is_superuser=True,
        is_active=True,
    )

    if created:
        user.password = make_password('test')
        user.save() 
Example 11
Project: python   Author: Yeah-Kun   File: crypto.py    License: Apache License 2.0 6 votes vote down vote up
def salted_hmac(key_salt, value, secret=None):
    """
    Returns the HMAC-SHA1 of 'value', using a key generated from key_salt and a
    secret (which defaults to settings.SECRET_KEY).

    A different key_salt should be passed in for every application of HMAC.
    """
    if secret is None:
        secret = settings.SECRET_KEY

    key_salt = force_bytes(key_salt)
    secret = force_bytes(secret)

    # We need to generate a derived key from our base key.  We can do this by
    # passing the key_salt and our base key through a pseudo-random function and
    # SHA1 works nicely.
    key = hashlib.sha1(key_salt + secret).digest()

    # If len(key_salt + secret) > sha_constructor().block_size, the above
    # line is redundant and could be replaced by key = key_salt + secret, since
    # the hmac module does the same thing for keys longer than the block size.
    # However, we need to ensure that we *always* do this.
    return hmac.new(key, msg=force_bytes(value), digestmod=hashlib.sha1) 
Example 12
Project: python   Author: Yeah-Kun   File: crypto.py    License: Apache License 2.0 6 votes vote down vote up
def get_random_string(length=12,
                      allowed_chars='abcdefghijklmnopqrstuvwxyz'
                                    'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
    """
    Returns a securely generated random string.

    The default length of 12 with the a-z, A-Z, 0-9 character set returns
    a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
    """
    if not using_sysrandom:
        # This is ugly, and a hack, but it makes things better than
        # the alternative of predictability. This re-seeds the PRNG
        # using a value that is hard for an attacker to predict, every
        # time a random string is required. This may change the
        # properties of the chosen random sequence slightly, but this
        # is better than absolute predictability.
        random.seed(
            hashlib.sha256(
                ("%s%s%s" % (
                    random.getstate(),
                    time.time(),
                    settings.SECRET_KEY)).encode('utf-8')
            ).digest())
    return ''.join(random.choice(allowed_chars) for i in range(length)) 
Example 13
Project: luscan-devel   Author: blackye   File: crypto.py    License: GNU General Public License v2.0 6 votes vote down vote up
def salted_hmac(key_salt, value, secret=None):
    """
    Returns the HMAC-SHA1 of 'value', using a key generated from key_salt and a
    secret (which defaults to settings.SECRET_KEY).

    A different key_salt should be passed in for every application of HMAC.
    """
    if secret is None:
        secret = settings.SECRET_KEY

    # We need to generate a derived key from our base key.  We can do this by
    # passing the key_salt and our base key through a pseudo-random function and
    # SHA1 works nicely.
    key = hashlib.sha1((key_salt + secret).encode('utf-8')).digest()

    # If len(key_salt + secret) > sha_constructor().block_size, the above
    # line is redundant and could be replaced by key = key_salt + secret, since
    # the hmac module does the same thing for keys longer than the block size.
    # However, we need to ensure that we *always* do this.
    return hmac.new(key, msg=force_bytes(value), digestmod=hashlib.sha1) 
Example 14
Project: luscan-devel   Author: blackye   File: crypto.py    License: GNU General Public License v2.0 6 votes vote down vote up
def get_random_string(length=12,
                      allowed_chars='abcdefghijklmnopqrstuvwxyz'
                                    'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
    """
    Returns a securely generated random string.

    The default length of 12 with the a-z, A-Z, 0-9 character set returns
    a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
    """
    if not using_sysrandom:
        # This is ugly, and a hack, but it makes things better than
        # the alternative of predictability. This re-seeds the PRNG
        # using a value that is hard for an attacker to predict, every
        # time a random string is required. This may change the
        # properties of the chosen random sequence slightly, but this
        # is better than absolute predictability.
        random.seed(
            hashlib.sha256(
                ("%s%s%s" % (
                    random.getstate(),
                    time.time(),
                    settings.SECRET_KEY)).encode('utf-8')
                ).digest())
    return ''.join([random.choice(allowed_chars) for i in range(length)]) 
Example 15
Project: openhgsenti   Author: drexly   File: crypto.py    License: Apache License 2.0 6 votes vote down vote up
def salted_hmac(key_salt, value, secret=None):
    """
    Returns the HMAC-SHA1 of 'value', using a key generated from key_salt and a
    secret (which defaults to settings.SECRET_KEY).

    A different key_salt should be passed in for every application of HMAC.
    """
    if secret is None:
        secret = settings.SECRET_KEY

    key_salt = force_bytes(key_salt)
    secret = force_bytes(secret)

    # We need to generate a derived key from our base key.  We can do this by
    # passing the key_salt and our base key through a pseudo-random function and
    # SHA1 works nicely.
    key = hashlib.sha1(key_salt + secret).digest()

    # If len(key_salt + secret) > sha_constructor().block_size, the above
    # line is redundant and could be replaced by key = key_salt + secret, since
    # the hmac module does the same thing for keys longer than the block size.
    # However, we need to ensure that we *always* do this.
    return hmac.new(key, msg=force_bytes(value), digestmod=hashlib.sha1) 
Example 16
Project: openhgsenti   Author: drexly   File: crypto.py    License: Apache License 2.0 6 votes vote down vote up
def get_random_string(length=12,
                      allowed_chars='abcdefghijklmnopqrstuvwxyz'
                                    'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
    """
    Returns a securely generated random string.

    The default length of 12 with the a-z, A-Z, 0-9 character set returns
    a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
    """
    if not using_sysrandom:
        # This is ugly, and a hack, but it makes things better than
        # the alternative of predictability. This re-seeds the PRNG
        # using a value that is hard for an attacker to predict, every
        # time a random string is required. This may change the
        # properties of the chosen random sequence slightly, but this
        # is better than absolute predictability.
        random.seed(
            hashlib.sha256(
                ("%s%s%s" % (
                    random.getstate(),
                    time.time(),
                    settings.SECRET_KEY)).encode('utf-8')
            ).digest())
    return ''.join(random.choice(allowed_chars) for i in range(length)) 
Example 17
Project: cruzz   Author: Monal5031   File: backends.py    License: MIT License 6 votes vote down vote up
def _authenticate_credentials(self, request, token):
        """
        Try to authenticate the given credentials. If authentication is
        successful, return the user and token. If not, throw an error.
        """
        try:
            payload = jwt.decode(token, settings.SECRET_KEY)
        except Exception as e:
            msg = 'Invalid authentication. Could not decode token.'
            print(e)
            raise exceptions.AuthenticationFailed(msg)

        try:
            user = User.objects.get(pk=payload['id'])
        except User.DoesNotExist:
            msg = 'No user matching this token was found.'
            raise exceptions.AuthenticationFailed(msg)

        if not user.is_active:
            msg = 'This user has been deactivated.'
            raise exceptions.AuthenticationFailed(msg)

        return user, token 
Example 18
Project: python2017   Author: bpgc-cte   File: crypto.py    License: MIT License 6 votes vote down vote up
def salted_hmac(key_salt, value, secret=None):
    """
    Returns the HMAC-SHA1 of 'value', using a key generated from key_salt and a
    secret (which defaults to settings.SECRET_KEY).

    A different key_salt should be passed in for every application of HMAC.
    """
    if secret is None:
        secret = settings.SECRET_KEY

    key_salt = force_bytes(key_salt)
    secret = force_bytes(secret)

    # We need to generate a derived key from our base key.  We can do this by
    # passing the key_salt and our base key through a pseudo-random function and
    # SHA1 works nicely.
    key = hashlib.sha1(key_salt + secret).digest()

    # If len(key_salt + secret) > sha_constructor().block_size, the above
    # line is redundant and could be replaced by key = key_salt + secret, since
    # the hmac module does the same thing for keys longer than the block size.
    # However, we need to ensure that we *always* do this.
    return hmac.new(key, msg=force_bytes(value), digestmod=hashlib.sha1) 
Example 19
Project: python2017   Author: bpgc-cte   File: crypto.py    License: MIT License 6 votes vote down vote up
def get_random_string(length=12,
                      allowed_chars='abcdefghijklmnopqrstuvwxyz'
                                    'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
    """
    Returns a securely generated random string.

    The default length of 12 with the a-z, A-Z, 0-9 character set returns
    a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
    """
    if not using_sysrandom:
        # This is ugly, and a hack, but it makes things better than
        # the alternative of predictability. This re-seeds the PRNG
        # using a value that is hard for an attacker to predict, every
        # time a random string is required. This may change the
        # properties of the chosen random sequence slightly, but this
        # is better than absolute predictability.
        random.seed(
            hashlib.sha256(
                ("%s%s%s" % (
                    random.getstate(),
                    time.time(),
                    settings.SECRET_KEY)).encode('utf-8')
            ).digest())
    return ''.join(random.choice(allowed_chars) for i in range(length)) 
Example 20
Project: mirandum   Author: google   File: views.py    License: Apache License 2.0 6 votes vote down vote up
def auth_return(request):
  if not xsrfutil.validate_token(settings.SECRET_KEY, str(request.GET['state']),
                                 request.user.username):
    return  HttpResponseBadRequest()
  credential = FLOW.step2_exchange(request.GET)
  
  credential = TwitchCredentials.from_json(credential.to_json())
  http = httplib2.Http()
  http = credential.authorize(http)
  
  resp, data = http.request("https://api.twitch.tv/kraken/user")
  data = json.loads(data)
  print data
  ac = TwitchAppCreds(user=request.user, label=data['name'])
  ac.save()
  return HttpResponseRedirect("/accounts/")
  return render(request, "twitchaccount/label.html", data) 
Example 21
Project: mirandum   Author: google   File: views.py    License: Apache License 2.0 6 votes vote down vote up
def auth_return(request):
  if not xsrfutil.validate_token(settings.SECRET_KEY, str(request.GET['state']),
                                 request.user.username):
    return  HttpResponseBadRequest()
  credential = FLOW.step2_exchange(request.GET)
  http = httplib2.Http()
  http = credential.authorize(http)
  resp, data = http.request("https://api.patreon.com/oauth2/api/current_user")
  data = json.loads(data)
  name = data['data']['attributes'].get("full_name") or "(unnamed)"
  internal_label = "%s-%s" % (request.user.id, name)
  ac = PatreonAppCreds(user=request.user, label=internal_label)
  ac.save()
  storage = Storage(PatreonCredentialsModel, 'id', ac, 'credential')
  storage.put(credential)
  pu = PatreonUpdate(credentials=ac, user=request.user, type="patreon")
  pu.save()
  return HttpResponseRedirect("/patreon/") 
Example 22
Project: trace-examples   Author: DataDog   File: backends.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _authenticate_credentials(self, request, token):
        """
        Try to authenticate the given credentials. If authentication is
        successful, return the user and token. If not, throw an error.
        """
        try:
            payload = jwt.decode(token, settings.SECRET_KEY)
        except:
            msg = 'Invalid authentication. Could not decode token.'
            raise exceptions.AuthenticationFailed(msg)

        try:
            user = User.objects.get(pk=payload['id'])
        except User.DoesNotExist:
            msg = 'No user matching this token was found.'
            raise exceptions.AuthenticationFailed(msg)

        if not user.is_active:
            msg = 'This user has been deactivated.'
            raise exceptions.AuthenticationFailed(msg)

        return (user, token) 
Example 23
Project: django-encrypted-id   Author: amitu   File: __init__.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def encode(the_id, sub_key):
    assert 0 <= the_id < 2 ** 64

    version = 1

    crc = binascii.crc32(str(the_id).encode('utf-8')) & 0xffffffff

    message = struct.pack(b"<IQI", crc, the_id, version)
    assert len(message) == 16

    key = settings.SECRET_KEY
    iv = hashlib.sha256((key + sub_key).encode('ascii')).digest()[:16]
    cypher = AES.new(key[:32].encode('utf-8'), AES.MODE_CBC, iv)

    eid = base64.urlsafe_b64encode(cypher.encrypt(message)).replace(b"=", b"")
    return eid.decode("utf-8") 
Example 24
Project: django-request-token   Author: yunojuno   File: utils.py    License: MIT License 6 votes vote down vote up
def decode(
    token: bytes,
    options: Optional[Dict[str, bool]] = None,
    check_claims: Optional[Sequence[str]] = None,
    algorithms: Optional[List[str]] = None,
) -> dict:
    """Decode JWT payload and check for 'jti', 'sub' claims."""
    if not options:
        options = DEFAULT_DECODE_OPTIONS
    if not check_claims:
        check_claims = MANDATORY_CLAIMS
    if not algorithms:
        # default encode algorithm - see PyJWT.encode
        algorithms = ["HS256"]
    decoded = jwt_decode(
        token, settings.SECRET_KEY, algorithms=algorithms, options=options
    )
    check_mandatory_claims(decoded, claims=check_claims)
    return decoded 
Example 25
Project: django-phone-verify   Author: CuriousLearner   File: base.py    License: GNU General Public License v3.0 5 votes vote down vote up
def generate_session_token(cls, phone_number):
        """
        Returns a unique session_token for
        identifying a particular device in subsequent calls.
        """
        data = {"phone_number": phone_number, "nonce": random.random()}
        return jwt.encode(data, django_settings.SECRET_KEY).decode() 
Example 26
Project: coursys   Author: sfu-fas   File: models.py    License: GNU General Public License v3.0 5 votes vote down vote up
def save(self, *args, **kwargs):
        res = super().save(*args, **kwargs)
        if 'secret' not in self.config:
            # Ensure we are saved (so self.id is filled), and if the secret isn't there, fill it in.
            self.config['secret'] = string_hash(settings.SECRET_KEY) + self.id
            super().save(*args, **kwargs)
        return res 
Example 27
Project: GTDWeb   Author: lanbing510   File: signing.py    License: GNU General Public License v2.0 5 votes vote down vote up
def get_cookie_signer(salt='django.core.signing.get_cookie_signer'):
    Signer = import_string(settings.SIGNING_BACKEND)
    key = force_bytes(settings.SECRET_KEY)
    return Signer(b'django.http.cookies' + key, salt=salt) 
Example 28
Project: GTDWeb   Author: lanbing510   File: signing.py    License: GNU General Public License v2.0 5 votes vote down vote up
def dumps(obj, key=None, salt='django.core.signing', serializer=JSONSerializer, compress=False):
    """
    Returns URL-safe, sha1 signed base64 compressed JSON string. If key is
    None, settings.SECRET_KEY is used instead.

    If compress is True (not the default) checks if compressing using zlib can
    save some space. Prepends a '.' to signify compression. This is included
    in the signature, to protect against zip bombs.

    Salt can be used to namespace the hash, so that a signed string is
    only valid for a given namespace. Leaving this at the default
    value or re-using a salt value across different parts of your
    application without good cause is a security risk.

    The serializer is expected to return a bytestring.
    """
    data = serializer().dumps(obj)

    # Flag for if it's been compressed or not
    is_compressed = False

    if compress:
        # Avoid zlib dependency unless compress is being used
        compressed = zlib.compress(data)
        if len(compressed) < (len(data) - 1):
            data = compressed
            is_compressed = True
    base64d = b64_encode(data)
    if is_compressed:
        base64d = b'.' + base64d
    return TimestampSigner(key, salt=salt).sign(base64d) 
Example 29
Project: GTDWeb   Author: lanbing510   File: signing.py    License: GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, key=None, sep=':', salt=None):
        # Use of native strings in all versions of Python
        self.sep = force_str(sep)
        self.key = key or settings.SECRET_KEY
        self.salt = force_str(salt or
            '%s.%s' % (self.__class__.__module__, self.__class__.__name__)) 
Example 30
Project: django-cryptography   Author: georgemarshall   File: conf.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def configure(self):
        backend = self.configured_data['BACKEND']
        digest = self.configured_data['DIGEST']
        salt = self.configured_data['SALT']
        # Key Derivation Function
        kdf = pbkdf2.PBKDF2HMAC(
            algorithm=digest,
            length=digest.digest_size,
            salt=salt,
            iterations=30000,
            backend=backend,
        )
        self.configured_data['KEY'] = kdf.derive(
            force_bytes(self.configured_data['KEY'] or settings.SECRET_KEY))
        return self.configured_data