Python Glossary Русский

all Python 3hashlibfunction

hashlib.pbkdf2_hmac()

password hashing

Slow, salted password hashing (PBKDF2): turns a password into a key that is expensive to brute-force. Use it for passwords instead of sha256().

Syntax

hashlib.pbkdf2_hmac(hash_name, password, salt, iterations, dklen=None)

The iteration count sets the strength, and it is ridiculously low in tutorial examples: for SHA-256 hundreds of thousands are recommended (OWASP says 600,000), and a call should take a noticeable fraction of a second. The salt is 16+ random bytes from os.urandom() or secrets, unique per user, stored next to the hash along with the iteration count. Password and salt must be bytes: encode a string with .encode(), otherwise TypeError.

Examples

import hashlib
# 1000 итераций — только для примера; на деле — сотни тысяч
key = hashlib.pbkdf2_hmac('sha256', b'password', b'salt', 1000)
print(key.hex()[:16], len(key))  # → 632c2812e46d4604 32
import hashlib
try:
    hashlib.pbkdf2_hmac('sha256', 'password', b'salt', 1000)
except TypeError as e:
    print(e)  # → a bytes-like object is required, not 'str'

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy