summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorEli Collins <elic@assurancetechnologies.com>2013-04-10 14:09:46 -0400
committerEli Collins <elic@assurancetechnologies.com>2013-04-10 14:09:46 -0400
commit1fc43ec17f2b8e453283bcd9f0c3e8962703a15d (patch)
tree0c576658fbcf15f219977f7e786060e72b114436
parent3a1e9b9acb0662dad130d813473553a3233ede76 (diff)
downloadpasslib-1fc43ec17f2b8e453283bcd9f0c3e8962703a15d.tar.gz
pbkdf cleanups
* updated sha1_crypt to use get_keyed_prf(), should be ~10% faster * documented get_hash_info() and get_keyed_prf()
-rw-r--r--CHANGES5
-rw-r--r--admin/benchmarks.py10
-rw-r--r--docs/lib/passlib.utils.pbkdf2.rst3
-rw-r--r--passlib/handlers/sha1_crypt.py14
-rw-r--r--passlib/utils/pbkdf2.py56
5 files changed, 47 insertions, 41 deletions
diff --git a/CHANGES b/CHANGES
index 85ceb55..7bef039 100644
--- a/CHANGES
+++ b/CHANGES
@@ -23,6 +23,10 @@ Minor Changes
* The shared :class:`!PasswordHash` unittests now check all hash handlers for
basic thread-safety (motivated by the pybcrypt 0.2 concurrency bug).
+* The internal support module :mod:`passlib.utils.pbkdf2` has gained
+ to new helpers: :func:`~passlib.utils.pbkdf2.get_hash_info`
+ and :func:`~passlib.utils.pbkdf2.get_keyed_prf`.
+
Deprecations
------------
:class:`passlib.utils.handlers.HasManyBackends` internal API change
@@ -37,7 +41,6 @@ Deprecations
Todo
----
-* unittests and documentation for get_hash_info(), get_keyed_prf()
* Thread safety audit and tests for CryptContext, HasManyBackends, and lazy-init subclasses.
**1.6.1** (2012-08-02)
diff --git a/admin/benchmarks.py b/admin/benchmarks.py
index ff3480a..6d8db93 100644
--- a/admin/benchmarks.py
+++ b/admin/benchmarks.py
@@ -242,6 +242,16 @@ def test_phpass():
handler.verify(OTHER, hash)
return helper
+@benchmark.constructor()
+def test_sha1_crypt():
+ from passlib.hash import sha1_crypt as handler
+ kwds = dict(salt='.'*8, rounds=10000)
+ def helper():
+ hash = handler.encrypt(SECRET, **kwds)
+ handler.verify(SECRET, hash)
+ handler.verify(OTHER, hash)
+ return helper
+
#=============================================================================
# crypto utils
#=============================================================================
diff --git a/docs/lib/passlib.utils.pbkdf2.rst b/docs/lib/passlib.utils.pbkdf2.rst
index f8eb89f..7fa9f98 100644
--- a/docs/lib/passlib.utils.pbkdf2.rst
+++ b/docs/lib/passlib.utils.pbkdf2.rst
@@ -26,7 +26,10 @@ PKCS#5 Key Derivation Functions
Helper Functions
================
.. autofunction:: norm_hash_name
+.. autofunction:: get_hash_info
+
.. autofunction:: get_prf
+.. autofunction:: get_keyed_prf
..
given how this module is expanding in scope,
diff --git a/passlib/handlers/sha1_crypt.py b/passlib/handlers/sha1_crypt.py
index cd70826..8ec6346 100644
--- a/passlib/handlers/sha1_crypt.py
+++ b/passlib/handlers/sha1_crypt.py
@@ -9,9 +9,9 @@
import logging; log = logging.getLogger(__name__)
# site
# pkg
-from passlib.utils import classproperty, h64, safe_crypt, test_crypt
-from passlib.utils.compat import b, u, unicode
-from passlib.utils.pbkdf2 import get_prf
+from passlib.utils import h64, safe_crypt, test_crypt
+from passlib.utils.compat import b, u, unicode, irange
+from passlib.utils.pbkdf2 import get_keyed_prf
import passlib.utils.handlers as uh
# local
__all__ = [
@@ -19,7 +19,6 @@ __all__ = [
#=============================================================================
# sha1-crypt
#=============================================================================
-_hmac_sha1 = get_prf("hmac-sha1")[0]
_BNULL = b('\x00')
class sha1_crypt(uh.HasManyBackends, uh.HasRounds, uh.HasSalt, uh.GenericHandler):
@@ -129,10 +128,9 @@ class sha1_crypt(uh.HasManyBackends, uh.HasRounds, uh.HasSalt, uh.GenericHandler
# NOTE: this seed value is NOT the same as the config string
result = (u("%s$sha1$%s") % (self.salt, rounds)).encode("ascii")
# NOTE: this algorithm is essentially PBKDF1, modified to use HMAC.
- r = 0
- while r < rounds:
- result = _hmac_sha1(secret, result)
- r += 1
+ keyed_hmac = get_keyed_prf("hmac-sha1", secret)[0]
+ for _ in irange(rounds):
+ result = keyed_hmac(result)
return h64.encode_transposed_bytes(result, self._chk_offsets).decode("ascii")
_chk_offsets = [
diff --git a/passlib/utils/pbkdf2.py b/passlib/utils/pbkdf2.py
index 6fe93c0..6985ed5 100644
--- a/passlib/utils/pbkdf2.py
+++ b/passlib/utils/pbkdf2.py
@@ -27,7 +27,6 @@ __all__ = [
# hash utils
"norm_hash_name",
"get_hash_info",
- ##"get_hash_const,"
# prf utils
"get_prf",
@@ -150,7 +149,7 @@ def norm_hash_name(name, format="hashlib"):
return row[idx]
def _get_hash_const(name):
- """internal helper for :func:`get_hash_const`"""
+ """internal helper used by :func:`get_hash_info`"""
# typecheck
if not isinstance(name, str):
raise TypeError("expected digest name")
@@ -196,19 +195,20 @@ def _get_hash_const(name):
_ghi_cache = {}
def get_hash_info(name):
- """lookup hash constructor & stats by name.
+ """Lookup hash constructor & stats by name.
- This is a thin wrapper around hashlib, which looks up a hash by name,
- and returns a hash constructor, along the digest & block sizes.
+ This is a thin wrapper around :mod:`hashlib`. It looks up a hash by name,
+ and returns a hash constructor, along with the digest & block sizes.
Calls to this method are cached, making it a lot faster
than looking up a hash and then creating a temporary instance
- in order to read the digest size.
+ in order to read the digest size. Additionally, this function includes
+ workarounds and fallbacks for various VM-specific issues.
:arg name: hashlib-compatible name of hash function
- :raises ValueError: if hash is unknown
+ :raises ValueError: if hash is unknown or unsupported.
- :returns: `(constuctor, digest_size, block_size)`
+ :returns: `(hash_constructor, digest_size, block_size)`
.. versionadded:: 1.7
"""
@@ -225,14 +225,6 @@ def get_hash_info(name):
record = _ghi_cache[name] = (const, tmp.digest_size, tmp.block_size)
return record
-##def get_hash_const(name):
-## """convenience wrapper around :func:`get_hash_info` which just
-## returns a hash constructor"""
-## try:
-## return _ghi_cache[name][0]
-## except KeyError:
-## return get_hash_info(name)[0]
-
#=============================================================================
# prf lookup
#=============================================================================
@@ -304,33 +296,33 @@ def _get_hmac_prf(digest):
_prf_cache = {}
def get_prf(name):
- """lookup pseudo-random family (prf) by name.
+ """Lookup pseudo-random family (PRF) by name.
:arg name:
- this must be the name of a recognized prf.
- currently this only recognizes names with the format
+ This must be the name of a recognized prf.
+ Currently this only recognizes names with the format
:samp:`hmac-{digest}`, where :samp:`{digest}`
is the name of a hash function such as
``md5``, ``sha256``, etc.
- this can also be a callable with the signature
- ``prf(secret, message) -> digest``,
+ This can also be a callable with the signature
+ ``prf_func(secret, message) -> digest``,
in which case it will be returned unchanged.
:raises ValueError: if the name is not known
:raises TypeError: if the name is not a callable or string
:returns:
- a tuple of :samp:`({func}, {digest_size})`.
+ a tuple of :samp:`({prf_func}, {digest_size})`, where:
- * :samp:`{func}` is a function implementing
- the specified prf, and has the signature
- ``func(secret, message) -> digest``.
+ * :samp:`{prf_func}` is a function implementing
+ the specified PRF, and has the signature
+ ``prf_func(secret, message) -> digest``.
* :samp:`{digest_size}` is an integer indicating
the number of bytes the function returns.
- usage example::
+ Usage example::
>>> from passlib.utils.pbkdf2 import get_prf
>>> hmac_sha256, dsize = get_prf("hmac-sha256")
@@ -340,8 +332,8 @@ def get_prf(name):
32
>>> digest = hmac_sha256('password', 'message')
- this function will attempt to return the fastest implementation
- it can find; if M2Crypto is present, and supports the specified prf,
+ This function will attempt to return the fastest implementation
+ it can find. Primarily, if M2Crypto is present, and supports the specified PRF,
:func:`M2Crypto.EVP.hmac` will be used behind the scenes.
"""
global _prf_cache
@@ -399,8 +391,8 @@ def _get_keyed_hmac_prf(digest, key):
return kprf, digest_size
def get_keyed_prf(name, key):
- """lookup psuedo-random function family by name,
- and return function associated with specific key.
+ """Lookup psuedo-random function family by name,
+ and return a psuedo-random function bound to a specific key.
:arg name:
name of psuedorandom family.
@@ -410,8 +402,8 @@ def get_keyed_prf(name, key):
key encoded as bytes.
:returns:
- tuple of :samp:`({func}, {digest_size})`,
- where function has signature `func(message) -> digest`.
+ tuple of :samp:`({bound_prf_func}, {digest_size})`,
+ where function has signature `bound_prf_func(message) -> digest`.
.. versionadded:: 1.7
"""