Ticket #19799: 19799-identify_hasher.diff

File 19799-identify_hasher.diff, 2.0 KB (added by Claude Paroz, 12 years ago)

Proof of concept about identify_hasher asking hashers

  • django/contrib/auth/hashers.py

    diff --git a/django/contrib/auth/hashers.py b/django/contrib/auth/hashers.py
    index bd760cd..27201a7 100644
    a b def identify_hasher(encoded):  
    123123    """
    124124    Returns an instance of a loaded password hasher.
    125125
    126     Identifies hasher algorithm by examining encoded hash, and calls
    127     get_hasher() to return hasher. Raises ValueError if
    128     algorithm cannot be identified, or if hasher is not loaded.
     126    Identifies hasher algorithm by asking each hasher in turn if they are
     127    accepting the encoded hash format. Raises ValueError if
     128    algorithm cannot be identified.
    129129    """
    130     if ((len(encoded) == 32 and '$' not in encoded) or
    131             (len(encoded) == 37 and encoded.startswith('md5$$'))):
    132         algorithm = 'unsalted_md5'
    133     else:
    134         algorithm = encoded.split('$', 1)[0]
    135     return get_hasher(algorithm)
     130    if HASHERS is None:
     131        load_hashers()
     132    for algorithm, hasher in HASHERS.items():
     133        if hasher.supports(encoded):
     134            return hasher
     135    raise ValueError(
     136        "Unable to find any hasher accepting a hash starting with '%s...'" % (
     137            encoded[:12],))
    136138
    137139
    138140def mask_hash(hash, show=6, char="*"):
    class BasePasswordHasher(object):  
    172174        raise ValueError("Hasher '%s' doesn't specify a library attribute" %
    173175                         self.__class__)
    174176
     177    def supports(self, hash_):
     178        """
     179        Return True if hash_ is supported by this hasher.
     180        """
     181        return self.algorithm == hash_.split('$', 1)[0]
     182
    175183    def salt(self):
    176184        """
    177185        Generates a cryptographically secure nonce salt in ascii
    class UnsaltedMD5PasswordHasher(BasePasswordHasher):  
    361369    """
    362370    algorithm = "unsalted_md5"
    363371
     372    def supports(self, hash_):
     373        return (len(hash_) == 32 and '$' not in hash_) or \
     374               (len(hash_) == 37 and hash_.startswith('md5$$'))
     375
    364376    def salt(self):
    365377        return ''
    366378
Back to Top