@@ -0,0 +1,2214 @@
+# coding: utf8%0A%22%22%22%0A%0A    Securely hash and check passwords using PBKDF2.%0A%0A    Use random salts to protect againt rainbow tables, many iterations against%0A    brute-force, and constant-time comparaison againt timing attacks.%0A%0A    Keep parameters to the algorithm together with the hash so that we can%0A    change the parameters and keep older hashes working.%0A%0A    See more details at http://exyr.org/2011/hashing-passwords/%0A%0A    Author: Simon Sapin%0A    License: BSD%0A%0A%22%22%22%0A%0Aimport hashlib%0Afrom os import urandom%0Afrom base64 import b64encode, b64decode%0Afrom itertools import izip%0A%0A# From https://github.com/mitsuhiko/python-pbkdf2%0Afrom pbkdf2 import pbkdf2_bin%0A%0A%0A# Parameters to PBKDF2. Only affect new passwords.%0ASALT_LENGTH = 12%0AKEY_LENGTH = 24%0AHASH_FUNCTION = 'sha256'  # Must be in hashlib.%0A# Linear to the hashing time. Adjust to be high but take a reasonable%0A# amount of time on your server. Measure with:%0A# python -m timeit -s 'import passwords as p' 'p.make_hash(%22something%22)'%0ACOST_FACTOR = 10000%0A%0A%0Adef make_hash(password):%0A    %22%22%22Generate a random salt and return a new hash for the password.%22%22%22%0A    if isinstance(password, unicode):%0A        password = password.encode('utf-8')%0A    salt = b64encode(urandom(SALT_LENGTH))%0A    return 'PBKDF2$%7B%7D$%7B%7D$%7B%7D$%7B%7D'.format(%0A        HASH_FUNCTION,%0A        COST_FACTOR,%0A        salt,%0A        b64encode(pbkdf2_bin(password, salt, COST_FACTOR, KEY_LENGTH,%0A                             getattr(hashlib, HASH_FUNCTION))))%0A%0A%0Adef check_hash(password, hash_):%0A    %22%22%22Check a password against an existing hash.%22%22%22%0A    if isinstance(password, unicode):%0A        password = password.encode('utf-8')%0A    algorithm, hash_function, cost_factor, salt, hash_a = hash_.split('$')%0A    assert algorithm == 'PBKDF2'%0A    hash_a = b64decode(hash_a)%0A    hash_b = pbkdf2_bin(password, salt, int(cost_factor), len(hash_a),%0A                        getattr(hashlib, hash_function))%0A    assert len(hash_a) == len(hash_b)  # we requested this from pbkdf2_bin()%0A    # Same as %22return hash_a == hash_b%22 but takes a constant time.%0A    # See http://carlos.bueno.org/2011/10/timing.html%0A    diff = 0%0A    for char_a, char_b in izip(hash_a, hash_b):%0A        diff %7C= ord(char_a) %5E ord(char_b)%0A    return diff == 0%0A

Add some glue code to hash salted passwords wit PBKDF2.