在选择正确的算法用于会话哈希时,大小是否重要。
我最近阅读了这篇文章,它建议使用漩涡为会话 ID 创建哈希。Whirlpool 生成一个 128 字符的哈希字符串,这个是不是太大了?
计划是将会话哈希存储在数据库中。使用 64 个字符字段 (sha256)、96 个字符字段 (sha384) 或 128 个字符字段 (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;
}