hash_password

pyhelpers.ops.hash_password(password, salt=None, salt_size=None, iterations=None, ret_hash=True, **kwargs)[source]

Hash a password using hashlib.pbkdf2_hmac (PBKDF2 algorithm with HMAC-SHA256).

See also [OPS-HP-1].

Parameters:
  • password (str | int | float | bytes) – Password to be hashed.

  • salt (bytes | str | None) – Optional salt data for hashing; if salt=None (default), it is generated by os.urandom(), which depends on salt_size; see also [OPS-HP-2].

  • salt_size (int | None) – Size of the salt in bytes, which is equivalent to size of the function os.urandom(); defaults to 128 if not specified.

  • iterations (int | None) – Number of iterations for PBKDF2, which is equivalent to size of the function hashlib.pbkdf2_hmac(); defaults to 100000 if not specified.

  • ret_hash (bool) – Whether to return the salt and key; defaults to True.

  • kwargs – [Optional] Additional parameters for the function hashlib.pbkdf2_hmac().

Returns:

Hashed password and salt as bytes (returned only if ret_hash=True).

Return type:

bytes | None

Examples:

>>> from pyhelpers.ops import hash_password, verify_password
>>> test_pwd = 'test%123'
>>> salt_size_ = 16
>>> sk = hash_password(password=test_pwd, salt_size=salt_size_)  # salt and key
>>> salt_data, key_data = sk[:salt_size_].hex(), sk[salt_size_:].hex()
>>> verify_password(password=test_pwd, salt=salt_data, key=key_data)
True
>>> test_pwd = b'test%123'
>>> sk = hash_password(password=test_pwd)
>>> salt_data, key_data = sk[:128].hex(), sk[128:].hex()
>>> verify_password(password=test_pwd, salt=salt_data, key=key_data)
True