Last active
November 15, 2022 23:47
-
-
Save djekl/663bb9e998192d0eef5db957d635d128 to your computer and use it in GitHub Desktop.
This is how you generate and compare a Postfix Salted SHA512 Hash in PHP. It assumes you have used an 8bit salt for your hash. Tested here on all PHP versions - https://3v4l.org/8qtW0
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$password = "chemicals1"; | |
$expected = "{SSHA512}w/lHn2LXfNletbfyLVYutBFqUjGPzhmptyleVlehUZSZdylZCt/sDmvkhTBV1Ln4f6rzXTdM6eOGr3LX7FgGCF5/fsbs0vVq"; | |
function generate_postfix_ssha512_hash($password, $salt = false) { | |
$hash_algo = "{SSHA512}"; | |
$salt_length = 8; | |
// generate a random salt if one isn't provided | |
$salt = empty($salt) ? random_bytes($salt_length) : $salt; | |
// hash our password with the salt | |
$hash = hash('sha512', "{$password}{$salt}", true); | |
// base64 encode the salt so we have a sane string | |
$hash = base64_encode("{$hash}{$salt}"); | |
// return our generated password hash with identifier | |
return "{$hash_algo}{$hash}"; | |
} | |
function compare_postfix_ssha512_hash($password, $valid_hash) { | |
$hash_algo = "{SSHA512}"; | |
$salt_length = 8; | |
// strip the identifier from the hash (if exists) | |
$valid_hash = str_replace($hash_algo, "", $valid_hash); | |
// get the salt from the valid hash | |
$salt = substr(base64_decode($valid_hash), -$salt_length); | |
// strip the salt from the end of the valid hash | |
$valid_hash = substr(base64_decode($valid_hash), 0, -$salt_length); | |
// hash our password with the salt | |
$hash = generate_postfix_ssha512_hash($password, $salt); | |
// strip the identifier from the hash (if exists) | |
$hash = str_replace($hash_algo, "", $hash); | |
// strip the salt from the end of the valid hash | |
$hash = substr(base64_decode($hash), 0, -$salt_length); | |
// return the comparison | |
return hash_equals($valid_hash, $hash); | |
} | |
var_dump(compare_postfix_ssha512_hash($password, $expected)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks