Skip to content

Store a password

A website never stores a password. It stores a hash, which is a value made from the password that cannot be turned back into it. This program makes a hash and checks two logins.

<?nvs
// This program stores a password as a hash and checks a login against it.
// `Core\Password::hash` returns a hash. You store the hash, never the password.
string $stored = Core\Password::hash('correct horse battery staple');
class Login
{
// Returns `true` when `$typed` is the password that `$stored` was made from.
public static function check(secret string $typed, string $stored): bool
{
return Core\Password::verify($typed, $stored);
}
}
// This prints `welcome` and then `wrong password`.
echo Login::check('correct horse battery staple', $stored) ? 'welcome' : 'wrong password', "\n";
echo Login::check('Correct horse battery staple', $stored) ? 'welcome' : 'wrong password', "\n";
Output
welcome
wrong password

Core\Password::hash returns a different hash each time, even for the same password. That is why you check a login with Core\Password::verify, and never compare two hashes.

Read Core\Password for needsRehash, which tells you when to make a new hash.