这种密码散列和匹配方法的安全性如何?

时间:2015-08-14 06:10:06

标签: php security hash cryptography passwords

我从一系列帖子和一些先验知识中获取信息,以实现以下哈希算法。然而,有很多关于哪些实现是安全且不安全的讨论。我的方法如何衡量?它安全吗?

public static function sha512($token,$cost = 50000,$salt = null) {
        $salt = ($salt == null) ? (generateToken(32)) : ($salt);
        $salt = '$6$rounds=' . $cost . '$' . $salt . ' $';
        return crypt($token, $salt);
}

public static function sha512Equals($token,$hash) {
    return (crypt($token,$hash) == $hash);
}


public static function generateToken($length,$characterPool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') {
    $token = '';
    $max = mb_strlen($characterPool);

    for ($i = 0;$i < $length;$i++){
        $token .= $characterPool[cryptorand(0,$max)];
    }

    return $token;
}

public static function cryptorand($min, $max) {
    $range = $max - $min;

    if ($range < 0) 
        return $min;

    $log = log($range, 2);
    $bytes = (int) ($log / 8) + 1; // length in bytes
    $bits = (int) $log + 1; // length in bits
    $filter = (int) (1 << $bits) - 1; // set all lower bits to 1

    do {
        $rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes)));
        $rnd = $rnd & $filter; // discard irrelevant bits
    } while ($rnd >= $range);

    return $min + $rnd;
}

这种方法安全吗? PHP中是否有更安全的方法用于散列令牌以及稍后与令牌匹配?任何批评都非常感激。

1 个答案:

答案 0 :(得分:3)

不,因为您最终信任crypt并且您没有在sha512Equals中使用时间常数比较。

也可能存在特定于平台的问题:openssl_random_pseudo_bytes并非必须具有加密安全性。我不知道你怎么知道crypt也使用SHA-512。

cryptorand中的计算略有偏差(例如,对于精确位于字节边界的$log的值),但幸运的是,这是由do / while循环检查的。< / p>

请改用password_hashpassword_verify功能。

相关问题