You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

892 line
30 KiB

  1. """passlib.crypto.digest -- crytographic helpers used by the password hashes in passlib
  2. .. versionadded:: 1.7
  3. """
  4. #=============================================================================
  5. # imports
  6. #=============================================================================
  7. from __future__ import division
  8. # core
  9. import hashlib
  10. import logging; log = logging.getLogger(__name__)
  11. try:
  12. # new in py3.4
  13. from hashlib import pbkdf2_hmac as _stdlib_pbkdf2_hmac
  14. if _stdlib_pbkdf2_hmac.__module__ == "hashlib":
  15. # builtin pure-python backends are slightly faster than stdlib's pure python fallback,
  16. # so only using stdlib's version if it's backed by openssl's pbkdf2_hmac()
  17. log.debug("ignoring pure-python hashlib.pbkdf2_hmac()")
  18. _stdlib_pbkdf2_hmac = None
  19. except ImportError:
  20. _stdlib_pbkdf2_hmac = None
  21. import re
  22. import os
  23. from struct import Struct
  24. from warnings import warn
  25. # site
  26. try:
  27. # https://pypi.python.org/pypi/fastpbkdf2/
  28. from fastpbkdf2 import pbkdf2_hmac as _fast_pbkdf2_hmac
  29. except ImportError:
  30. _fast_pbkdf2_hmac = None
  31. # pkg
  32. from passlib import exc
  33. from passlib.utils import join_bytes, to_native_str, join_byte_values, to_bytes, \
  34. SequenceMixin
  35. from passlib.utils.compat import irange, int_types, unicode_or_bytes_types, PY3
  36. from passlib.utils.decor import memoized_property
  37. # local
  38. __all__ = [
  39. # hash utils
  40. "lookup_hash",
  41. "HashInfo",
  42. "norm_hash_name",
  43. # hmac utils
  44. "compile_hmac",
  45. # kdfs
  46. "pbkdf1",
  47. "pbkdf2_hmac",
  48. ]
  49. #=============================================================================
  50. # generic constants
  51. #=============================================================================
  52. #: max 32-bit value
  53. MAX_UINT32 = (1 << 32) - 1
  54. #: max 64-bit value
  55. MAX_UINT64 = (1 << 64) - 1
  56. #=============================================================================
  57. # hash utils
  58. #=============================================================================
  59. #: list of known hash names, used by lookup_hash()'s _norm_hash_name() helper
  60. _known_hash_names = [
  61. # format: (hashlib/ssl name, iana name or standin, other known aliases ...)
  62. # hashes with official IANA-assigned names
  63. # (as of 2012-03 - http://www.iana.org/assignments/hash-function-text-names)
  64. ("md2", "md2"),
  65. ("md5", "md5"),
  66. ("sha1", "sha-1"),
  67. ("sha224", "sha-224", "sha2-224"),
  68. ("sha256", "sha-256", "sha2-256"),
  69. ("sha384", "sha-384", "sha2-384"),
  70. ("sha512", "sha-512", "sha2-512"),
  71. # TODO: add sha3 to this table.
  72. # hashlib/ssl-supported hashes without official IANA names,
  73. # (hopefully-) compatible stand-ins have been chosen.
  74. ("md4", "md4"),
  75. ("sha", "sha-0", "sha0"),
  76. ("ripemd", "ripemd"),
  77. ("ripemd160", "ripemd-160"),
  78. ]
  79. #: cache of hash info instances used by lookup_hash()
  80. _hash_info_cache = {}
  81. def _get_hash_aliases(name):
  82. """
  83. internal helper used by :func:`lookup_hash` --
  84. normalize arbitrary hash name to hashlib format.
  85. if name not recognized, returns dummy record and issues a warning.
  86. :arg name:
  87. unnormalized name
  88. :returns:
  89. tuple with 2+ elements: ``(hashlib_name, iana_name|None, ... 0+ aliases)``.
  90. """
  91. # normalize input
  92. orig = name
  93. if not isinstance(name, str):
  94. name = to_native_str(name, 'utf-8', 'hash name')
  95. name = re.sub("[_ /]", "-", name.strip().lower())
  96. if name.startswith("scram-"): # helper for SCRAM protocol (see passlib.handlers.scram)
  97. name = name[6:]
  98. if name.endswith("-plus"):
  99. name = name[:-5]
  100. # look through standard names and known aliases
  101. def check_table(name):
  102. for row in _known_hash_names:
  103. if name in row:
  104. return row
  105. result = check_table(name)
  106. if result:
  107. return result
  108. # try to clean name up some more
  109. m = re.match(r"(?i)^(?P<name>[a-z]+)-?(?P<rev>\d)?-?(?P<size>\d{3,4})?$", name)
  110. if m:
  111. # roughly follows "SHA2-256" style format, normalize representation,
  112. # and checked table.
  113. iana_name, rev, size = m.group("name", "rev", "size")
  114. if rev:
  115. iana_name += rev
  116. hashlib_name = iana_name
  117. if size:
  118. iana_name += "-" + size
  119. if rev:
  120. hashlib_name += "_"
  121. hashlib_name += size
  122. result = check_table(iana_name)
  123. if result:
  124. return result
  125. # not found in table, but roughly recognize format. use names we built up as fallback.
  126. log.info("normalizing unrecognized hash name %r => %r / %r",
  127. orig, hashlib_name, iana_name)
  128. else:
  129. # just can't make sense of it. return something
  130. iana_name = name
  131. hashlib_name = name.replace("-", "_")
  132. log.warning("normalizing unrecognized hash name and format %r => %r / %r",
  133. orig, hashlib_name, iana_name)
  134. return hashlib_name, iana_name
  135. def _get_hash_const(name):
  136. """
  137. internal helper used by :func:`lookup_hash` --
  138. lookup hash constructor by name
  139. :arg name:
  140. name (normalized to hashlib format, e.g. ``"sha256"``)
  141. :returns:
  142. hash constructor, e.g. ``hashlib.sha256()``;
  143. or None if hash can't be located.
  144. """
  145. # check hashlib.<attr> for an efficient constructor
  146. if not name.startswith("_") and name not in ("new", "algorithms"):
  147. try:
  148. return getattr(hashlib, name)
  149. except AttributeError:
  150. pass
  151. # check hashlib.new() in case SSL supports the digest
  152. new_ssl_hash = hashlib.new
  153. try:
  154. # new() should throw ValueError if alg is unknown
  155. new_ssl_hash(name, b"")
  156. except ValueError:
  157. pass
  158. else:
  159. # create wrapper function
  160. # XXX: is there a faster way to wrap this?
  161. def const(msg=b""):
  162. return new_ssl_hash(name, msg)
  163. const.__name__ = name
  164. const.__module__ = "hashlib"
  165. const.__doc__ = ("wrapper for hashlib.new(%r),\n"
  166. "generated by passlib.crypto.digest.lookup_hash()") % name
  167. return const
  168. # use builtin md4 as fallback when not supported by hashlib
  169. if name == "md4":
  170. from passlib.crypto._md4 import md4
  171. return md4
  172. # XXX: any other modules / registries we should check?
  173. # TODO: add pysha3 support.
  174. return None
  175. def lookup_hash(digest, return_unknown=False):
  176. """
  177. Returns a :class:`HashInfo` record containing information about a given hash function.
  178. Can be used to look up a hash constructor by name, normalize hash name representation, etc.
  179. :arg digest:
  180. This can be any of:
  181. * A string containing a :mod:`!hashlib` digest name (e.g. ``"sha256"``),
  182. * A string containing an IANA-assigned hash name,
  183. * A digest constructor function (e.g. ``hashlib.sha256``).
  184. Case is ignored, underscores are converted to hyphens,
  185. and various other cleanups are made.
  186. :param return_unknown:
  187. By default, this function will throw an :exc:`~passlib.exc.UnknownHashError` if no hash constructor
  188. can be found. However, if this flag is False, it will instead return a dummy record
  189. without a constructor function. This is mainly used by :func:`norm_hash_name`.
  190. :returns HashInfo:
  191. :class:`HashInfo` instance containing information about specified digest.
  192. Multiple calls resolving to the same hash should always
  193. return the same :class:`!HashInfo` instance.
  194. """
  195. # check for cached entry
  196. cache = _hash_info_cache
  197. try:
  198. return cache[digest]
  199. except (KeyError, TypeError):
  200. # NOTE: TypeError is to catch 'TypeError: unhashable type' (e.g. HashInfo)
  201. pass
  202. # resolve ``digest`` to ``const`` & ``name_record``
  203. cache_by_name = True
  204. if isinstance(digest, unicode_or_bytes_types):
  205. # normalize name
  206. name_list = _get_hash_aliases(digest)
  207. name = name_list[0]
  208. assert name
  209. # if name wasn't normalized to hashlib format,
  210. # get info for normalized name and reuse it.
  211. if name != digest:
  212. info = lookup_hash(name, return_unknown=return_unknown)
  213. if info.const is None:
  214. # pass through dummy record
  215. assert return_unknown
  216. return info
  217. cache[digest] = info
  218. return info
  219. # else look up constructor
  220. const = _get_hash_const(name)
  221. if const is None:
  222. if return_unknown:
  223. # return a dummy record (but don't cache it, so normal lookup still returns error)
  224. return HashInfo(None, name_list)
  225. else:
  226. raise exc.UnknownHashError(name)
  227. elif isinstance(digest, HashInfo):
  228. # handle border case where HashInfo is passed in.
  229. return digest
  230. elif callable(digest):
  231. # try to lookup digest based on it's self-reported name
  232. # (which we trust to be the canonical "hashlib" name)
  233. const = digest
  234. name_list = _get_hash_aliases(const().name)
  235. name = name_list[0]
  236. other_const = _get_hash_const(name)
  237. if other_const is None:
  238. # this is probably a third-party digest we don't know about,
  239. # so just pass it on through, and register reverse lookup for it's name.
  240. pass
  241. elif other_const is const:
  242. # if we got back same constructor, this is just a known stdlib constructor,
  243. # which was passed in before we had cached it by name. proceed normally.
  244. pass
  245. else:
  246. # if we got back different object, then ``const`` is something else
  247. # (such as a mock object), in which case we want to skip caching it by name,
  248. # as that would conflict with real hash.
  249. cache_by_name = False
  250. else:
  251. raise exc.ExpectedTypeError(digest, "digest name or constructor", "digest")
  252. # create new instance
  253. info = HashInfo(const, name_list)
  254. # populate cache
  255. cache[const] = info
  256. if cache_by_name:
  257. for name in name_list:
  258. if name: # (skips iana name if it's empty)
  259. assert cache.get(name) in [None, info], "%r already in cache" % name
  260. cache[name] = info
  261. return info
  262. #: UT helper for clearing internal cache
  263. lookup_hash.clear_cache = _hash_info_cache.clear
  264. def norm_hash_name(name, format="hashlib"):
  265. """Normalize hash function name (convenience wrapper for :func:`lookup_hash`).
  266. :arg name:
  267. Original hash function name.
  268. This name can be a Python :mod:`~hashlib` digest name,
  269. a SCRAM mechanism name, IANA assigned hash name, etc.
  270. Case is ignored, and underscores are converted to hyphens.
  271. :param format:
  272. Naming convention to normalize to.
  273. Possible values are:
  274. * ``"hashlib"`` (the default) - normalizes name to be compatible
  275. with Python's :mod:`!hashlib`.
  276. * ``"iana"`` - normalizes name to IANA-assigned hash function name.
  277. For hashes which IANA hasn't assigned a name for, this issues a warning,
  278. and then uses a heuristic to return a "best guess" name.
  279. :returns:
  280. Hash name, returned as native :class:`!str`.
  281. """
  282. info = lookup_hash(name, return_unknown=True)
  283. if not info.const:
  284. warn("norm_hash_name(): unknown hash: %r" % (name,), exc.PasslibRuntimeWarning)
  285. if format == "hashlib":
  286. return info.name
  287. elif format == "iana":
  288. return info.iana_name
  289. else:
  290. raise ValueError("unknown format: %r" % (format,))
  291. class HashInfo(SequenceMixin):
  292. """
  293. Record containing information about a given hash algorithm, as returned :func:`lookup_hash`.
  294. This class exposes the following attributes:
  295. .. autoattribute:: const
  296. .. autoattribute:: digest_size
  297. .. autoattribute:: block_size
  298. .. autoattribute:: name
  299. .. autoattribute:: iana_name
  300. .. autoattribute:: aliases
  301. This object can also be treated a 3-element sequence
  302. containing ``(const, digest_size, block_size)``.
  303. """
  304. #=========================================================================
  305. # instance attrs
  306. #=========================================================================
  307. #: Canonical / hashlib-compatible name (e.g. ``"sha256"``).
  308. name = None
  309. #: IANA assigned name (e.g. ``"sha-256"``), may be ``None`` if unknown.
  310. iana_name = None
  311. #: Tuple of other known aliases (may be empty)
  312. aliases = ()
  313. #: Hash constructor function (e.g. :func:`hashlib.sha256`)
  314. const = None
  315. #: Hash's digest size
  316. digest_size = None
  317. #: Hash's block size
  318. block_size = None
  319. def __init__(self, const, names):
  320. """
  321. initialize new instance.
  322. :arg const:
  323. hash constructor
  324. :arg names:
  325. list of 2+ names. should be list of ``(name, iana_name, ... 0+ aliases)``.
  326. names must be lower-case. only iana name may be None.
  327. """
  328. self.name = names[0]
  329. self.iana_name = names[1]
  330. self.aliases = names[2:]
  331. self.const = const
  332. if const is None:
  333. return
  334. hash = const()
  335. self.digest_size = hash.digest_size
  336. self.block_size = hash.block_size
  337. # do sanity check on digest size
  338. if len(hash.digest()) != hash.digest_size:
  339. raise RuntimeError("%r constructor failed sanity check" % self.name)
  340. # do sanity check on name.
  341. if hash.name != self.name:
  342. warn("inconsistent digest name: %r resolved to %r, which reports name as %r" %
  343. (self.name, const, hash.name), exc.PasslibRuntimeWarning)
  344. #=========================================================================
  345. # methods
  346. #=========================================================================
  347. def __repr__(self):
  348. return "<lookup_hash(%r): digest_size=%r block_size=%r)" % \
  349. (self.name, self.digest_size, self.block_size)
  350. def _as_tuple(self):
  351. return self.const, self.digest_size, self.block_size
  352. @memoized_property
  353. def supported_by_fastpbkdf2(self):
  354. """helper to detect if hash is supported by fastpbkdf2()"""
  355. if not _fast_pbkdf2_hmac:
  356. return None
  357. try:
  358. _fast_pbkdf2_hmac(self.name, b"p", b"s", 1)
  359. return True
  360. except ValueError:
  361. # "unsupported hash type"
  362. return False
  363. @memoized_property
  364. def supported_by_hashlib_pbkdf2(self):
  365. """helper to detect if hash is supported by hashlib.pbkdf2_hmac()"""
  366. if not _stdlib_pbkdf2_hmac:
  367. return None
  368. try:
  369. _stdlib_pbkdf2_hmac(self.name, b"p", b"s", 1)
  370. return True
  371. except ValueError:
  372. # "unsupported hash type"
  373. return False
  374. #=========================================================================
  375. # eoc
  376. #=========================================================================
  377. #=============================================================================
  378. # hmac utils
  379. #=============================================================================
  380. #: translation tables used by compile_hmac()
  381. _TRANS_5C = join_byte_values((x ^ 0x5C) for x in irange(256))
  382. _TRANS_36 = join_byte_values((x ^ 0x36) for x in irange(256))
  383. def compile_hmac(digest, key, multipart=False):
  384. """
  385. This function returns an efficient HMAC function, hardcoded with a specific digest & key.
  386. It can be used via ``hmac = compile_hmac(digest, key)``.
  387. :arg digest:
  388. digest name or constructor.
  389. :arg key:
  390. secret key as :class:`!bytes` or :class:`!unicode` (unicode will be encoded using utf-8).
  391. :param multipart:
  392. request a multipart constructor instead (see return description).
  393. :returns:
  394. By default, the returned function has the signature ``hmac(msg) -> digest output``.
  395. However, if ``multipart=True``, the returned function has the signature
  396. ``hmac() -> update, finalize``, where ``update(msg)`` may be called multiple times,
  397. and ``finalize() -> digest_output`` may be repeatedly called at any point to
  398. calculate the HMAC digest so far.
  399. The returned object will also have a ``digest_info`` attribute, containing
  400. a :class:`lookup_hash` instance for the specified digest.
  401. This function exists, and has the weird signature it does, in order to squeeze as
  402. provide as much efficiency as possible, by omitting much of the setup cost
  403. and features of the stdlib :mod:`hmac` module.
  404. """
  405. # all the following was adapted from stdlib's hmac module
  406. # resolve digest (cached)
  407. digest_info = lookup_hash(digest)
  408. const, digest_size, block_size = digest_info
  409. assert block_size >= 16, "block size too small"
  410. # prepare key
  411. if not isinstance(key, bytes):
  412. key = to_bytes(key, param="key")
  413. klen = len(key)
  414. if klen > block_size:
  415. key = const(key).digest()
  416. klen = digest_size
  417. if klen < block_size:
  418. key += b'\x00' * (block_size - klen)
  419. # create pre-initialized hash constructors
  420. _inner_copy = const(key.translate(_TRANS_36)).copy
  421. _outer_copy = const(key.translate(_TRANS_5C)).copy
  422. if multipart:
  423. # create multi-part function
  424. # NOTE: this is slightly slower than the single-shot version,
  425. # and should only be used if needed.
  426. def hmac():
  427. """generated by compile_hmac(multipart=True)"""
  428. inner = _inner_copy()
  429. def finalize():
  430. outer = _outer_copy()
  431. outer.update(inner.digest())
  432. return outer.digest()
  433. return inner.update, finalize
  434. else:
  435. # single-shot function
  436. def hmac(msg):
  437. """generated by compile_hmac()"""
  438. inner = _inner_copy()
  439. inner.update(msg)
  440. outer = _outer_copy()
  441. outer.update(inner.digest())
  442. return outer.digest()
  443. # add info attr
  444. hmac.digest_info = digest_info
  445. return hmac
  446. #=============================================================================
  447. # pbkdf1
  448. #=============================================================================
  449. def pbkdf1(digest, secret, salt, rounds, keylen=None):
  450. """pkcs#5 password-based key derivation v1.5
  451. :arg digest:
  452. digest name or constructor.
  453. :arg secret:
  454. secret to use when generating the key.
  455. may be :class:`!bytes` or :class:`unicode` (encoded using UTF-8).
  456. :arg salt:
  457. salt string to use when generating key.
  458. may be :class:`!bytes` or :class:`unicode` (encoded using UTF-8).
  459. :param rounds:
  460. number of rounds to use to generate key.
  461. :arg keylen:
  462. number of bytes to generate (if omitted / ``None``, uses digest's native size)
  463. :returns:
  464. raw :class:`bytes` of generated key
  465. .. note::
  466. This algorithm has been deprecated, new code should use PBKDF2.
  467. Among other limitations, ``keylen`` cannot be larger
  468. than the digest size of the specified hash.
  469. """
  470. # resolve digest
  471. const, digest_size, block_size = lookup_hash(digest)
  472. # validate secret & salt
  473. secret = to_bytes(secret, param="secret")
  474. salt = to_bytes(salt, param="salt")
  475. # validate rounds
  476. if not isinstance(rounds, int_types):
  477. raise exc.ExpectedTypeError(rounds, "int", "rounds")
  478. if rounds < 1:
  479. raise ValueError("rounds must be at least 1")
  480. # validate keylen
  481. if keylen is None:
  482. keylen = digest_size
  483. elif not isinstance(keylen, int_types):
  484. raise exc.ExpectedTypeError(keylen, "int or None", "keylen")
  485. elif keylen < 0:
  486. raise ValueError("keylen must be at least 0")
  487. elif keylen > digest_size:
  488. raise ValueError("keylength too large for digest: %r > %r" %
  489. (keylen, digest_size))
  490. # main pbkdf1 loop
  491. block = secret + salt
  492. for _ in irange(rounds):
  493. block = const(block).digest()
  494. return block[:keylen]
  495. #=============================================================================
  496. # pbkdf2
  497. #=============================================================================
  498. _pack_uint32 = Struct(">L").pack
  499. def pbkdf2_hmac(digest, secret, salt, rounds, keylen=None):
  500. """pkcs#5 password-based key derivation v2.0 using HMAC + arbitrary digest.
  501. :arg digest:
  502. digest name or constructor.
  503. :arg secret:
  504. passphrase to use to generate key.
  505. may be :class:`!bytes` or :class:`unicode` (encoded using UTF-8).
  506. :arg salt:
  507. salt string to use when generating key.
  508. may be :class:`!bytes` or :class:`unicode` (encoded using UTF-8).
  509. :param rounds:
  510. number of rounds to use to generate key.
  511. :arg keylen:
  512. number of bytes to generate.
  513. if omitted / ``None``, will use digest's native output size.
  514. :returns:
  515. raw bytes of generated key
  516. .. versionchanged:: 1.7
  517. This function will use the first available of the following backends:
  518. * `fastpbk2 <https://pypi.python.org/pypi/fastpbkdf2>`_
  519. * :func:`hashlib.pbkdf2_hmac` (only available in py2 >= 2.7.8, and py3 >= 3.4)
  520. * builtin pure-python backend
  521. See :data:`passlib.crypto.digest.PBKDF2_BACKENDS` to determine
  522. which backend(s) are in use.
  523. """
  524. # validate secret & salt
  525. secret = to_bytes(secret, param="secret")
  526. salt = to_bytes(salt, param="salt")
  527. # resolve digest
  528. digest_info = lookup_hash(digest)
  529. digest_size = digest_info.digest_size
  530. # validate rounds
  531. if not isinstance(rounds, int_types):
  532. raise exc.ExpectedTypeError(rounds, "int", "rounds")
  533. if rounds < 1:
  534. raise ValueError("rounds must be at least 1")
  535. # validate keylen
  536. if keylen is None:
  537. keylen = digest_size
  538. elif not isinstance(keylen, int_types):
  539. raise exc.ExpectedTypeError(keylen, "int or None", "keylen")
  540. elif keylen < 1:
  541. # XXX: could allow keylen=0, but want to be compat w/ stdlib
  542. raise ValueError("keylen must be at least 1")
  543. # find smallest block count s.t. keylen <= block_count * digest_size;
  544. # make sure block count won't overflow (per pbkdf2 spec)
  545. # this corresponds to throwing error if keylen > digest_size * MAX_UINT32
  546. # NOTE: stdlib will throw error at lower bound (keylen > MAX_SINT32)
  547. # NOTE: have do this before other backends checked, since fastpbkdf2 raises wrong error
  548. # (InvocationError, not OverflowError)
  549. block_count = (keylen + digest_size - 1) // digest_size
  550. if block_count > MAX_UINT32:
  551. raise OverflowError("keylen too long for digest")
  552. #
  553. # check for various high-speed backends
  554. #
  555. # ~3x faster than pure-python backend
  556. # NOTE: have to do this after above guards since fastpbkdf2 lacks bounds checks.
  557. if digest_info.supported_by_fastpbkdf2:
  558. return _fast_pbkdf2_hmac(digest_info.name, secret, salt, rounds, keylen)
  559. # ~1.4x faster than pure-python backend
  560. # NOTE: have to do this after fastpbkdf2 since hashlib-ssl is slower,
  561. # will support larger number of hashes.
  562. if digest_info.supported_by_hashlib_pbkdf2:
  563. return _stdlib_pbkdf2_hmac(digest_info.name, secret, salt, rounds, keylen)
  564. #
  565. # otherwise use our own implementation
  566. #
  567. # generated keyed hmac
  568. keyed_hmac = compile_hmac(digest, secret)
  569. # get helper to calculate pbkdf2 inner loop efficiently
  570. calc_block = _get_pbkdf2_looper(digest_size)
  571. # assemble & return result
  572. return join_bytes(
  573. calc_block(keyed_hmac, keyed_hmac(salt + _pack_uint32(i)), rounds)
  574. for i in irange(1, block_count + 1)
  575. )[:keylen]
  576. #-------------------------------------------------------------------------------------
  577. # pick best choice for pure-python helper
  578. # TODO: consider some alternatives, such as C-accelerated xor_bytes helper if available
  579. #-------------------------------------------------------------------------------------
  580. # NOTE: this env var is only present to support the admin/benchmark_pbkdf2 script
  581. _force_backend = os.environ.get("PASSLIB_PBKDF2_BACKEND") or "any"
  582. if PY3 and _force_backend in ["any", "from-bytes"]:
  583. from functools import partial
  584. def _get_pbkdf2_looper(digest_size):
  585. return partial(_pbkdf2_looper, digest_size)
  586. def _pbkdf2_looper(digest_size, keyed_hmac, digest, rounds):
  587. """
  588. py3-only implementation of pbkdf2 inner loop;
  589. uses 'int.from_bytes' + integer XOR
  590. """
  591. from_bytes = int.from_bytes
  592. BIG = "big" # endianess doesn't matter, just has to be consistent
  593. accum = from_bytes(digest, BIG)
  594. for _ in irange(rounds - 1):
  595. digest = keyed_hmac(digest)
  596. accum ^= from_bytes(digest, BIG)
  597. return accum.to_bytes(digest_size, BIG)
  598. _builtin_backend = "from-bytes"
  599. elif _force_backend in ["any", "unpack", "from-bytes"]:
  600. from struct import Struct
  601. from passlib.utils import sys_bits
  602. _have_64_bit = (sys_bits >= 64)
  603. #: cache used by _get_pbkdf2_looper
  604. _looper_cache = {}
  605. def _get_pbkdf2_looper(digest_size):
  606. """
  607. We want a helper function which performs equivalent of the following::
  608. def helper(keyed_hmac, digest, rounds):
  609. accum = digest
  610. for _ in irange(rounds - 1):
  611. digest = keyed_hmac(digest)
  612. accum ^= digest
  613. return accum
  614. However, no efficient way to implement "bytes ^ bytes" in python.
  615. Instead, using approach where we dynamically compile a helper function based
  616. on digest size. Instead of a single `accum` var, this helper breaks the digest
  617. into a series of integers.
  618. It stores these in a series of`accum_<i>` vars, and performs `accum ^= digest`
  619. by unpacking digest and perform xor for each "accum_<i> ^= digest_<i>".
  620. this keeps everything in locals, avoiding excessive list creation, encoding or decoding,
  621. etc.
  622. :param digest_size:
  623. digest size to compile for, in bytes. (must be multiple of 4).
  624. :return:
  625. helper function with call signature outlined above.
  626. """
  627. #
  628. # cache helpers
  629. #
  630. try:
  631. return _looper_cache[digest_size]
  632. except KeyError:
  633. pass
  634. #
  635. # figure out most efficient struct format to unpack digest into list of native ints
  636. #
  637. if _have_64_bit and not digest_size & 0x7:
  638. # digest size multiple of 8, on a 64 bit system -- use array of UINT64
  639. count = (digest_size >> 3)
  640. fmt = "=%dQ" % count
  641. elif not digest_size & 0x3:
  642. if _have_64_bit:
  643. # digest size multiple of 4, on a 64 bit system -- use array of UINT64 + 1 UINT32
  644. count = (digest_size >> 3)
  645. fmt = "=%dQI" % count
  646. count += 1
  647. else:
  648. # digest size multiple of 4, on a 32 bit system -- use array of UINT32
  649. count = (digest_size >> 2)
  650. fmt = "=%dI" % count
  651. else:
  652. # stopping here, cause no known hashes have digest size that isn't multiple of 4 bytes.
  653. # if needed, could go crazy w/ "H" & "B"
  654. raise NotImplementedError("unsupported digest size: %d" % digest_size)
  655. struct = Struct(fmt)
  656. #
  657. # build helper source
  658. #
  659. tdict = dict(
  660. digest_size=digest_size,
  661. accum_vars=", ".join("acc_%d" % i for i in irange(count)),
  662. digest_vars=", ".join("dig_%d" % i for i in irange(count)),
  663. )
  664. # head of function
  665. source = (
  666. "def helper(keyed_hmac, digest, rounds):\n"
  667. " '''pbkdf2 loop helper for digest_size={digest_size}'''\n"
  668. " unpack_digest = struct.unpack\n"
  669. " {accum_vars} = unpack_digest(digest)\n"
  670. " for _ in irange(1, rounds):\n"
  671. " digest = keyed_hmac(digest)\n"
  672. " {digest_vars} = unpack_digest(digest)\n"
  673. ).format(**tdict)
  674. # xor digest
  675. for i in irange(count):
  676. source += " acc_%d ^= dig_%d\n" % (i, i)
  677. # return result
  678. source += " return struct.pack({accum_vars})\n".format(**tdict)
  679. #
  680. # compile helper
  681. #
  682. code = compile(source, "<generated by passlib.crypto.digest._get_pbkdf2_looper()>", "exec")
  683. gdict = dict(irange=irange, struct=struct)
  684. ldict = dict()
  685. eval(code, gdict, ldict)
  686. helper = ldict['helper']
  687. if __debug__:
  688. helper.__source__ = source
  689. #
  690. # store in cache
  691. #
  692. _looper_cache[digest_size] = helper
  693. return helper
  694. _builtin_backend = "unpack"
  695. else:
  696. assert _force_backend in ["any", "hexlify"]
  697. # XXX: older & slower approach that used int(hexlify()),
  698. # keeping it around for a little while just for benchmarking.
  699. from binascii import hexlify as _hexlify
  700. from passlib.utils import int_to_bytes
  701. def _get_pbkdf2_looper(digest_size):
  702. return _pbkdf2_looper
  703. def _pbkdf2_looper(keyed_hmac, digest, rounds):
  704. hexlify = _hexlify
  705. accum = int(hexlify(digest), 16)
  706. for _ in irange(rounds - 1):
  707. digest = keyed_hmac(digest)
  708. accum ^= int(hexlify(digest), 16)
  709. return int_to_bytes(accum, len(digest))
  710. _builtin_backend = "hexlify"
  711. # helper for benchmark script -- disable hashlib, fastpbkdf2 support if builtin requested
  712. if _force_backend == _builtin_backend:
  713. _fast_pbkdf2_hmac = _stdlib_pbkdf2_hmac = None
  714. # expose info about what backends are active
  715. PBKDF2_BACKENDS = [b for b in [
  716. "fastpbkdf2" if _fast_pbkdf2_hmac else None,
  717. "hashlib-ssl" if _stdlib_pbkdf2_hmac else None,
  718. "builtin-" + _builtin_backend
  719. ] if b]
  720. # *very* rough estimate of relative speed (compared to sha256 using 'unpack' backend on 64bit arch)
  721. if "fastpbkdf2" in PBKDF2_BACKENDS:
  722. PBKDF2_SPEED_FACTOR = 3
  723. elif "hashlib-ssl" in PBKDF2_BACKENDS:
  724. PBKDF2_SPEED_FACTOR = 1.4
  725. else:
  726. # remaining backends have *some* difference in performance, but not enough to matter
  727. PBKDF2_SPEED_FACTOR = 1
  728. #=============================================================================
  729. # eof
  730. #=============================================================================