根据PHP中的SSHA256哈希验证密码


Validate a password against an SSHA256 hash in PHP

对于Dovecot的身份验证,我使用SSHA256哈希,但我不知道如何根据现有哈希验证给定的密码。以下PHP函数(在web中找到)用于创建SSHA256哈希:

function ssha256($pw) {
        $salt = make_salt();
        return "{SSHA256}" . base64_encode( hash('sha256', $pw . $salt, true ) . $salt );
}
function make_salt() {
        $len   = 4;
        $bytes = array();
        for ($i = 0; $i < $len; $i++ ) {
                $bytes[] = rand(1,255);
        }
        $salt_str = '';
        foreach ($bytes as $b) {
                $salt_str .= pack('C', $b);
        }
        return $salt_str;
}

示例输出:{SSHA256}lGq49JTKmBC49AUrk7wLyQVmeZ7cGl/V13A9QbY4RVKchckL

我必须提取盐吗?但是怎么提取呢?我完全迷失了解决问题的方法,有人对此有任何暗示吗?

感谢大家的帮助!

哦,很抱歉,我不得不使用SSHA256,因为Dovecot 1.2.15只支持这些方案:CRYPT MD5 MD5-CRYPT SHA SHA1 SHA256 SMD5 SSHA SSHA256 PLAIN CLEARTEXT CRAM-MD5 HMAC-MD5 DIGEST-MD5 PLAIN-MD4 PLAIN-MD5 LDAP-MD5 LANMAN NTLM OTP SKEY RPA

您不应该使用SHA家族进行密码哈希。它们,专为的速度哈希文件而设计。您需要将pashword哈希设置为昂贵。使用bcrypt、PHPass,或者只使用我自己滚动的这个类(但直到你学会在其中挖洞):

class PassHash {
    public static function rand_str($length) {
        $total = $length % 2;
        $output = "";
        if ($total !== 0) {
            $count = floor($length / 2);
            $output .= ".";
        } else $count = $length / 2;
        $bytes = openssl_random_pseudo_bytes($count);
        $output .= bin2hex($bytes);
        // warning: prepending with a dot if the length is odd.
        // this can be very dangerous. no clue why you'd want your
        // bcrypt salt to do this, but /shrug
        return $output;
    }
    // 2y is an exploit fix, and an improvement over 2a. Only available in 5.4.0+
    public static function hash($input) {
        return crypt($input, "$2y$13$" . self::rand_str(22));
    }
    // legacy support, add exception handling and fall back to <= 5.3.0
    public static function hash_weak($input) {
        return crypt($input, "$2a$13$" . self::rand_str(22));
    }
    public static function compare($input, $hash) {
        return (crypt($input, $hash) === $hash);
    }
}

您必须对给定的明文进行散列,并将该散列与您存储的散列进行比较。盐存储在散列中,并且应该是随机的。如果你喜欢,可以加一个胡椒。您还应该使工作速率可变,这样您就可以在需要时随时更改工作速率,并且系统仍然可以工作。


如果像你所说的那样,你没有办法实现这一点,你可以按如下方式解压缩哈希:

function unpack_hash($hash) {
        $hash = base64_decode($hash);
        $split = str_split($hash, 64);
        return array("salt" => $split[1], "hash" => $split[0]);

这是因为SHA256是256位或64个十六进制字符。您可以始终假设前64个字符是散列

您需要将salt与散列值一起存储。

当您需要验证密码时,只需使用用户输入的密码+存储的salt再次计算哈希即可。如果散列匹配,则用户输入了正确的密码。

对于您的格式,首先使用base64_decode,结果的最后4个字节将是salt。