示例#1
0
 def encode(self, password, salt):
     argon2 = self._load_library()
     data = argon2.low_level.hash_secret(
         force_bytes(password),
         force_bytes(salt),
         time_cost=self.time_cost,
         memory_cost=self.memory_cost,
         parallelism=self.parallelism,
         hash_len=argon2.DEFAULT_HASH_LENGTH,
         type=argon2.low_level.Type.I,
     )
     return self.algorithm + data.decode('ascii')
示例#2
0
 def verify(self, password, encoded):
     argon2 = self._load_library()
     algorithm, rest = encoded.split('$', 1)
     assert algorithm == self.algorithm
     try:
         return argon2.low_level.verify_secret(
             force_bytes('$' + rest),
             force_bytes(password),
             type=argon2.low_level.Type.I,
         )
     except argon2.exceptions.VerificationError:
         return False
示例#3
0
def _generate_cache_key(handler, method, header_list, key_prefix):
    """Return a cache key from the headers given in the header list."""
    ctx = hashlib.md5()
    request = handler.request
    for header in header_list:
        value = request.headers.get(header)
        if value is not None:
            ctx.update(force_bytes(value))
    url = hashlib.md5(force_bytes(iri_to_uri(request.full_url())))
    cache_key = 'cache.cache_page.%s.%s.%s.%s' % (
        key_prefix, method, url.hexdigest(), ctx.hexdigest())
    return _i18n_cache_key_suffix(handler, cache_key)
示例#4
0
    def encode(self, password, salt):
        bcrypt = self._load_library()
        # Hash the password prior to using bcrypt to prevent password
        # truncation as described in #20138.
        if self.digest is not None:
            # Use binascii.hexlify() because a hex encoded bytestring is str.
            password = binascii.hexlify(
                self.digest(force_bytes(password)).digest())
        else:
            password = force_bytes(password)

        data = bcrypt.hashpw(password, salt)
        return "%s$%s" % (self.algorithm, force_text(data))
示例#5
0
 def harden_runtime(self, password, encoded):
     _, data = encoded.split('$', 1)
     salt = data[:29]  # Length of the salt in bcrypt.
     rounds = data.split('$')[2]
     # work factor is logarithmic, adding one doubles the load.
     diff = 2**(self.rounds - int(rounds)) - 1
     while diff > 0:
         self.encode(password, force_bytes(salt))
         diff -= 1
示例#6
0
 def _key_to_file(self, key, version=None):
     """
     Convert a key into a cache file path. Basically this is the
     root cache path joined with the md5sum of the key and a suffix.
     """
     key = self.make_key(key, version=version)
     self.validate_key(key)
     return os.path.join(
         self._dir, ''.join(
             [hashlib.md5(force_bytes(key)).hexdigest(),
              self.cache_suffix]))
示例#7
0
 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('anthill.application')
             logger.warning(str(e))
         return {}
示例#8
0
def loads(s,
          key=None,
          salt='anthill.framework.core.signing',
          serializer=JSONSerializer,
          max_age=None):
    """
    Reverse of dumps(), raise BadSignature if signature fails.

    The serializer is expected to accept a bytestring.
    """
    # TimestampSigner.unsign() returns str but base64 and zlib compression
    # operate on bytes.
    base64d = force_bytes(
        TimestampSigner(key, salt=salt).unsign(s, max_age=max_age))
    decompress = False
    if base64d[:1] == b'.':
        # It's compressed; uncompress it first
        base64d = base64d[1:]
        decompress = True
    data = b64_decode(base64d)
    if decompress:
        data = zlib.decompress(data)
    return serializer().loads(data)
示例#9
0
def get_cookie_signer(salt='anthill.framework.core.signing.get_cookie_signer'):
    Signer = import_string(settings.SIGNING_BACKEND)
    key = force_bytes(settings.SECRET_KEY)
    return Signer(b'anthill.http.cookies' + key, salt=salt)
示例#10
0
 def encode(self, password, salt):
     assert salt == ''
     return hashlib.md5(force_bytes(password)).hexdigest()
示例#11
0
 def encode(self, password, salt):
     assert salt == ''
     hash = hashlib.sha1(force_bytes(password)).hexdigest()
     return 'sha1$$%s' % hash
示例#12
0
 def encode(self, password, salt):
     assert password is not None
     assert salt and '$' not in salt
     hash = hashlib.md5(force_bytes(salt + password)).hexdigest()
     return "%s$%s$%s" % (self.algorithm, salt, hash)
示例#13
0
 def verify(self, password, encoded):
     algorithm, data = encoded.split('$', 1)
     assert algorithm == self.algorithm
     encoded_2 = self.encode(password, force_bytes(data))
     return constant_time_compare(encoded, encoded_2)
示例#14
0
def _generate_cache_header_key(key_prefix, handler):
    """Return a cache key for the header cache."""
    request = handler.request
    url = hashlib.md5(force_bytes(iri_to_uri(request.full_url())))
    cache_key = 'cache.cache_header.%s.%s' % (key_prefix, url.hexdigest())
    return _i18n_cache_key_suffix(handler, cache_key)
示例#15
0
def make_template_fragment_key(fragment_name, vary_on=None):
    if vary_on is None:
        vary_on = ()
    key = ':'.join(quote(str(var)) for var in vary_on)
    args = hashlib.md5(force_bytes(key))
    return TEMPLATE_FRAGMENT_KEY_TEMPLATE % (fragment_name, args.hexdigest())