PHP password_hash, password_verify, and hash_hmac

PHP has a ready-made, safe way to store passwords. password_hash creates a salted hash with a slow algorithm (bcrypt by default). The result contains the algorithm, the cost, and the random salt, so it can be stored in one database column, and password_verify checks a login attempt against it. Never write your own password scheme with md5 or sha1.

PHP
<?php
$hash = password_hash("correct horse", PASSWORD_DEFAULT);
echo "algorithm: ", password_get_info($hash)["algoName"], "\n";
echo "right password: ", password_verify("correct horse", $hash) ? "accepted" : "rejected", "\n";
echo "wrong password: ", password_verify("wrong guess", $hash) ? "accepted" : "rejected", "\n";
echo "hashes differ for equal passwords: ",
    password_hash("correct horse", PASSWORD_DEFAULT) !== $hash ? "yes" : "no", "\n";

$tag = hash_hmac("sha256", "what do ya want for nothing?", "Jefe");
echo $tag, "\n";
$again = hash_hmac("sha256", "what do ya want for nothing?", "Jefe");
echo "valid: ", hash_equals($tag, $again) ? "yes" : "no", "\n";
$forged = hash_hmac("sha256", "what do ya want for something?", "Jefe");
echo "forged valid: ", hash_equals($tag, $forged) ? "yes" : "no", "\n";
Read the full lesson