Another security question

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

"Steve D'Aprano"  wrote in message 
news:585d57d5$0$1587$c3e8da3$5496439d at
> There is a stdlib PBKDF2. If you want to avoid third-party dependencies, 
> use that.

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 

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), 
        == bytes.fromhex(dk))

pwd = 'this is my secret passphrase'

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

["sha256", "2cd1150b98dab7219136c8deceda00e3", 100000, 

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.


More information about the Python-list mailing list