php - session 哈希大小重要吗?

标签 php algorithm session hash sessionid

在选择用于 session 哈希的正确算法时,大小是否重要。

我最近读了这个article它建议使用漩涡池为 session ID 创建哈希。 Whirlpool 生成一个 128 个字符的哈希字符串,这是否太大了?

计划是将 session 哈希存储在数据库中。使用 64 个字符字段 (sha256)、96 个字符字段 (sha384) 或 128 个字符字段 (whirlpool) 之间有很大区别吗?最初为 whirlpool 提出的争论之一是速度与其他算法相比,但从速度结果来看 sha384 并不太公平。

可以选择截断散列以使其小于 128 个字符。

我确实修改了原始代码片段,以允许根据需要更改算法。

更新:有一些关于字符串被散列的讨论,所以我包含了代码。


function generateUniqueId($maxLength = null) {
    $entropy = '';

    // try ssl first
    if (function_exists('openssl_random_pseudo_bytes')) {
        $entropy = openssl_random_pseudo_bytes(64, $strong);
        // skip ssl since it wasn't using the strong algo
        if($strong !== true) {
            $entropy = '';
        }
    }

    // add some basic mt_rand/uniqid combo
    $entropy .= uniqid(mt_rand(), true);

    // try to read from the windows RNG
    if (class_exists('COM')) {
        try {
            $com = new COM('CAPICOM.Utilities.1');
            $entropy .= base64_decode($com->GetRandom(64, 0));
        } catch (Exception $ex) {
        }
    }

    // try to read from the unix RNG
    if (is_readable('/dev/urandom')) {
        $h = fopen('/dev/urandom', 'rb');
        $entropy .= fread($h, 64);
        fclose($h);
    }

    // create hash
    $hash = hash('whirlpool', $entropy);
    // truncate hash if max length imposed
    if ($maxLength) {
        return substr($hash, 0, $maxLength);
    }
    return $hash;
}

最佳答案

创建散列所花费的时间并不重要,只要您的数据库正确索引,存储方法也不应成为主要因素。

然而,哈希值每次都必须随客户端的请求一起传输,通常作为 cookie。大 cookie 可以为每个请求增加少量额外时间。参见 Yahoo!'s page performance best practices想要查询更多的信息。更小的 cookie,即更小的散列,有好处。

总的来说,大型散列函数可能是不合理的。对于它们有限的范围,良好的旧 md5 和 sha1 可能只是作为 session token 背后的来源。

关于php - session 哈希大小重要吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3089435/

相关文章:

php - CodeIgniter - 使用事务插入多个表

php - 在 php 文件中声明将在 JS/jQuery 中访问的变量

.net - "Level Generation"疯狂病毒游戏算法

algorithm - 一个红黑案例问题

java - 有没有办法将 OGNL 与 Struts2 UI 标签绑定(bind)

php - 如何将可变模式与 preg_match 一起使用?

algorithm - 给定多条水平线和垂直线,如何找到其中包含子矩形的所有矩形?

java - 如何在 Java Web App 中限制每个用户一次只能进行一个 session ?

c# - HttpContext.Current.Session 不清楚的行为 bool 值

php - 达到最大函数嵌套级别 '256',正在中止