djekl
9/6/2016 - 7:57 AM

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 o

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

<?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));