Another security question

Frank Millman frank at chagford.com
Sat Dec 24 03:43:32 EST 2016


"Steve D'Aprano"  wrote in message 
news:585d57d5$0$1587$c3e8da3$5496439d at news.astraweb.com...
>
> There is a stdlib PBKDF2. If you want to avoid third-party dependencies, 
> use that.
>
> https://docs.python.org/3.4/library/hashlib.html#hashlib.pbkdf2_hmac
>

Thanks for the pointer.

>From the docs - 15.1.3. Key derivation -
"The number of iterations should be chosen based on the hash algorithm and 
computing power. As of 2013, at least 100,000 iterations of SHA-256 are 
suggested."

So FWIW, this is what I have come up with -

from hashlib import pbkdf2_hmac as kdf
from secrets import token_bytes
from json import loads, dumps

def gen_password(pwd):
    hash_name = 'sha256'
    salt = token_bytes(16)
    iterations = 100000
    dk = kdf(hash_name, pwd.encode('utf-8'), salt, iterations)
    return dumps([hash_name, salt.hex(), iterations, dk.hex()])

def chk_password(pwd_hash, pwd):
    hash_name, salt, iterations, dk = loads(pwd_hash)
    return (kdf(hash_name, pwd.encode('utf-8'), bytes.fromhex(salt), 
iterations)
        == bytes.fromhex(dk))

pwd = 'this is my secret passphrase'

pwd_hash = gen_password(pwd)
print(pwd_hash)
print(chk_password(pwd_hash, pwd))

["sha256", "2cd1150b98dab7219136c8deceda00e3", 100000, 
"6301857d79554c3e2035fc779e4903f098ba2df36536028b72952426a5773f0a"]
True

I know that 'rolling your own' is a no-no when it comes to security. I don't 
know whether this falls into that category or not, but I will run with it 
for now.

Frank





More information about the Python-list mailing list