diff options
Diffstat (limited to 'passlib/crypto/digest.py')
-rw-r--r-- | passlib/crypto/digest.py | 67 |
1 files changed, 35 insertions, 32 deletions
diff --git a/passlib/crypto/digest.py b/passlib/crypto/digest.py index 90e0cad..c1b9769 100644 --- a/passlib/crypto/digest.py +++ b/passlib/crypto/digest.py @@ -5,7 +5,6 @@ #============================================================================= # imports #============================================================================= -from __future__ import division # core import hashlib import logging; log = logging.getLogger(__name__) @@ -31,9 +30,8 @@ except ImportError: _fast_pbkdf2_hmac = None # pkg from passlib import exc -from passlib.utils import join_bytes, to_native_str, join_byte_values, to_bytes, \ - SequenceMixin, as_bool -from passlib.utils.compat import irange, int_types, unicode_or_bytes_types, PY3, error_from +from passlib.utils import join_bytes, to_native_str, to_bytes, SequenceMixin, as_bool +from passlib.utils.compat import unicode_or_bytes from passlib.utils.decor import memoized_property # local __all__ = [ @@ -126,7 +124,7 @@ def _gen_fallback_info(): not invoked at runtime. """ out = {} - for alg in sorted(hashlib.algorithms_available | set(["md4"])): + for alg in sorted(hashlib.algorithms_available | {"md4"}): info = lookup_hash(alg) out[info.name] = (info.digest_size, info.block_size) return out @@ -298,7 +296,7 @@ def lookup_hash(digest, # *, # resolve ``digest`` to ``const`` & ``name_record`` cache_by_name = True - if isinstance(digest, unicode_or_bytes_types): + if isinstance(digest, unicode_or_bytes): # normalize name name_list = _get_hash_aliases(digest) name = name_list[0] @@ -584,7 +582,7 @@ mock_fips_mode = False #: algorithms allowed under FIPS mode (subset of hashlib.algorithms_available); #: per https://csrc.nist.gov/Projects/Hash-Functions FIPS 202 list. -_fips_algorithms = set([ +_fips_algorithms = { # FIPS 180-4 and FIPS 202 'sha1', 'sha224', @@ -601,7 +599,7 @@ _fips_algorithms = set([ 'sha3_512', 'shake_128', 'shake_256', -]) +} def _set_mock_fips_mode(enable=True): @@ -622,8 +620,8 @@ if as_bool(os.environ.get("PASSLIB_MOCK_FIPS_MODE")): #============================================================================= #: translation tables used by compile_hmac() -_TRANS_5C = join_byte_values((x ^ 0x5C) for x in irange(256)) -_TRANS_36 = join_byte_values((x ^ 0x36) for x in irange(256)) +_TRANS_5C = bytes((x ^ 0x5C) for x in range(256)) +_TRANS_36 = bytes((x ^ 0x36) for x in range(256)) def compile_hmac(digest, key, multipart=False): """ @@ -634,7 +632,7 @@ def compile_hmac(digest, key, multipart=False): digest name or constructor. :arg key: - secret key as :class:`!bytes` or :class:`!unicode` (unicode will be encoded using utf-8). + secret key as :class:`!bytes` or :class:`!str` (str will be encoded using utf-8). :param multipart: request a multipart constructor instead (see return description). @@ -713,11 +711,11 @@ def pbkdf1(digest, secret, salt, rounds, keylen=None): :arg secret: secret to use when generating the key. - may be :class:`!bytes` or :class:`unicode` (encoded using UTF-8). + may be :class:`!bytes` or :class:`str` (encoded using UTF-8). :arg salt: salt string to use when generating key. - may be :class:`!bytes` or :class:`unicode` (encoded using UTF-8). + may be :class:`!bytes` or :class:`str` (encoded using UTF-8). :param rounds: number of rounds to use to generate key. @@ -742,7 +740,7 @@ def pbkdf1(digest, secret, salt, rounds, keylen=None): salt = to_bytes(salt, param="salt") # validate rounds - if not isinstance(rounds, int_types): + if not isinstance(rounds, int): raise exc.ExpectedTypeError(rounds, "int", "rounds") if rounds < 1: raise ValueError("rounds must be at least 1") @@ -750,7 +748,7 @@ def pbkdf1(digest, secret, salt, rounds, keylen=None): # validate keylen if keylen is None: keylen = digest_size - elif not isinstance(keylen, int_types): + elif not isinstance(keylen, int): raise exc.ExpectedTypeError(keylen, "int or None", "keylen") elif keylen < 0: raise ValueError("keylen must be at least 0") @@ -760,7 +758,7 @@ def pbkdf1(digest, secret, salt, rounds, keylen=None): # main pbkdf1 loop block = secret + salt - for _ in irange(rounds): + for _ in range(rounds): block = const(block).digest() return block[:keylen] @@ -778,11 +776,11 @@ def pbkdf2_hmac(digest, secret, salt, rounds, keylen=None): :arg secret: passphrase to use to generate key. - may be :class:`!bytes` or :class:`unicode` (encoded using UTF-8). + may be :class:`!bytes` or :class:`str` (encoded using UTF-8). :arg salt: salt string to use when generating key. - may be :class:`!bytes` or :class:`unicode` (encoded using UTF-8). + may be :class:`!bytes` or :class:`str` (encoded using UTF-8). :param rounds: number of rounds to use to generate key. @@ -814,7 +812,7 @@ def pbkdf2_hmac(digest, secret, salt, rounds, keylen=None): digest_size = digest_info.digest_size # validate rounds - if not isinstance(rounds, int_types): + if not isinstance(rounds, int): raise exc.ExpectedTypeError(rounds, "int", "rounds") if rounds < 1: raise ValueError("rounds must be at least 1") @@ -822,7 +820,7 @@ def pbkdf2_hmac(digest, secret, salt, rounds, keylen=None): # validate keylen if keylen is None: keylen = digest_size - elif not isinstance(keylen, int_types): + elif not isinstance(keylen, int): raise exc.ExpectedTypeError(keylen, "int or None", "keylen") elif keylen < 1: # XXX: could allow keylen=0, but want to be compat w/ stdlib @@ -866,7 +864,7 @@ def pbkdf2_hmac(digest, secret, salt, rounds, keylen=None): # assemble & return result return join_bytes( calc_block(keyed_hmac, keyed_hmac(salt + _pack_uint32(i)), rounds) - for i in irange(1, block_count + 1) + for i in range(1, block_count + 1) )[:keylen] #------------------------------------------------------------------------------------- @@ -876,7 +874,7 @@ def pbkdf2_hmac(digest, secret, salt, rounds, keylen=None): # NOTE: this env var is only present to support the admin/benchmark_pbkdf2 script _force_backend = os.environ.get("PASSLIB_PBKDF2_BACKEND") or "any" -if PY3 and _force_backend in ["any", "from-bytes"]: +if _force_backend in ["any", "from-bytes"]: from functools import partial def _get_pbkdf2_looper(digest_size): @@ -890,14 +888,19 @@ if PY3 and _force_backend in ["any", "from-bytes"]: from_bytes = int.from_bytes BIG = "big" # endianess doesn't matter, just has to be consistent accum = from_bytes(digest, BIG) - for _ in irange(rounds - 1): + for _ in range(rounds - 1): digest = keyed_hmac(digest) accum ^= from_bytes(digest, BIG) return accum.to_bytes(digest_size, BIG) _builtin_backend = "from-bytes" -elif _force_backend in ["any", "unpack", "from-bytes"]: +elif _force_backend in ["unpack"]: + + # XXX: should run bench_pbkdf2() to verify; + # but think this can be removed now that we're always on python 3 + # (the from_bytes method should always be faster) + from struct import Struct from passlib.utils import sys_bits @@ -912,7 +915,7 @@ elif _force_backend in ["any", "unpack", "from-bytes"]: def helper(keyed_hmac, digest, rounds): accum = digest - for _ in irange(rounds - 1): + for _ in range(rounds - 1): digest = keyed_hmac(digest) accum ^= digest return accum @@ -969,8 +972,8 @@ elif _force_backend in ["any", "unpack", "from-bytes"]: # tdict = dict( digest_size=digest_size, - accum_vars=", ".join("acc_%d" % i for i in irange(count)), - digest_vars=", ".join("dig_%d" % i for i in irange(count)), + accum_vars=", ".join("acc_%d" % i for i in range(count)), + digest_vars=", ".join("dig_%d" % i for i in range(count)), ) # head of function @@ -979,13 +982,13 @@ elif _force_backend in ["any", "unpack", "from-bytes"]: " '''pbkdf2 loop helper for digest_size={digest_size}'''\n" " unpack_digest = struct.unpack\n" " {accum_vars} = unpack_digest(digest)\n" - " for _ in irange(1, rounds):\n" + " for _ in range(1, rounds):\n" " digest = keyed_hmac(digest)\n" " {digest_vars} = unpack_digest(digest)\n" ).format(**tdict) # xor digest - for i in irange(count): + for i in range(count): source += " acc_%d ^= dig_%d\n" % (i, i) # return result @@ -995,7 +998,7 @@ elif _force_backend in ["any", "unpack", "from-bytes"]: # compile helper # code = compile(source, "<generated by passlib.crypto.digest._get_pbkdf2_looper()>", "exec") - gdict = dict(irange=irange, struct=struct) + gdict = dict(struct=struct) ldict = dict() eval(code, gdict, ldict) helper = ldict['helper'] @@ -1011,7 +1014,7 @@ elif _force_backend in ["any", "unpack", "from-bytes"]: _builtin_backend = "unpack" else: - assert _force_backend in ["any", "hexlify"] + assert _force_backend in ["hexlify"] # XXX: older & slower approach that used int(hexlify()), # keeping it around for a little while just for benchmarking. @@ -1025,7 +1028,7 @@ else: def _pbkdf2_looper(keyed_hmac, digest, rounds): hexlify = _hexlify accum = int(hexlify(digest), 16) - for _ in irange(rounds - 1): + for _ in range(rounds - 1): digest = keyed_hmac(digest) accum ^= int(hexlify(digest), 16) return int_to_bytes(accum, len(digest)) |