NAME

Database::BI::Password - Hash and check the login password

VERSION

0.024.0

SYNOPSIS

use Database::BI::Password qw(hash_password verify_password is_password_hash);

my $hash = hash_password('correct horse battery staple');
# pbkdf2-sha256$200000$<salt>$<key>

verify_password('correct horse battery staple', $hash);   # 1
verify_password('wrong', $hash);                          # 0

DESCRIPTION

The login (config password_hash, see "Logging in" in Database::BI) stores only a hash of the password, never the password. The hash is PBKDF2-HMAC-SHA256 (RFC 8018) with a random 16-byte salt and a 32-byte key, written as pbkdf2-sha256$<rounds>$<salt>$<key>, the salt and key in base64 without padding. script/database-bi password makes one.

FUNCTIONS

hash_password

my $hash = hash_password($password, rounds => 200_000);

API SPECIFICATION

INPUT

$password: string, required, not empty, not a reference, and not ending in a
           NUL byte (HMAC pads a short key with NULs, so "x" and "x\0" would
           be one password); a character string is hashed as UTF-8
rounds:    integer, optional, 10_000 to 100_000_000 (default 200_000).
           Domains: 9_999 and below, above 100_000_000, a fractional or
           signed number, an exponent, spaces, a newline and non-ASCII
           digits are refused; 10_000, 10_001, 99_999_999 and
           100_000_000 are accepted.  The password's length is not
           limited (one over 64 bytes is hashed once first, which HMAC
           does anyway); a string whose UTF-8 flag is on is hashed as
           its UTF-8 bytes, so it matches the same text typed as bytes
salt:      16 bytes (characters no higher than U+00FF), optional (default
           random); for tests

OUTPUT

The hash string. Croaks on a missing or reference password, one ending in a NUL byte, rounds out of range, or a salt of another length or not made of bytes; the messages are in %Database::BI::Password::MESSAGES. Crypt::URandom, which makes the salt, croaks when the system has no source of random bytes.

verify_password

my $ok = verify_password($password, $hash);

API SPECIFICATION

INPUT

$password: string
$hash:     string, as hash_password returns

OUTPUT

1 when the password is the one hashed, else 0, including for a missing password or a hash that is not one. Every byte of the key is compared, so the time taken does not depend on how much of it matched.

is_password_hash

is_password_hash($value);

API SPECIFICATION

INPUT

$value: anything

OUTPUT

1 when the value is a hash verify_password can check, else 0.

AUTHOR

Nigel Horne <njh@nigelhorne.com>

LICENCE AND COPYRIGHT

Copyright 2026 Nigel Horne.

Usage is subject to the GPL2 licence terms.