hash_equals

(PHP 5 >= 5.6.0, PHP 7, PHP 8)

hash_equals可防止时序攻击的字符串比较

说明

hash_equals(string $known_string, string $user_string): bool

比较两个字符串,无论它们是否相等,本函数的时间消耗是恒定的。

本函数可以用在需要防止时序攻击的字符串比较场景中, 例如,可以用在比较 crypt() 密码散列值的场景。

参数

known_string

已知长度的、要参与比较的 string

user_string

用户提供的字符串

返回值

当两个字符串相等时返回 true,否则返回 false

范例

示例 #1 hash_equals() 例程

<?php
$expected
= crypt('12345', '$2a$07$usesomesillystringforsalt$');
$correct = crypt('12345', '$2a$07$usesomesillystringforsalt$');
$incorrect = crypt('apple', '$2a$07$usesomesillystringforsalt$');

var_dump(hash_equals($expected, $correct));
var_dump(hash_equals($expected, $incorrect));
?>

以上例程会输出:

bool(true)
bool(false)

注释

注意:

要想成功进行比较,那么所提供的 2 个参数必须是相同长度的字符串。 如果所提供的字符串长度不同,那么本函数会立即返回 false, 在时序攻击的场景下,已知字符串的长度可能会被泄露。

注意:

非常重要的一点是,用户提供的字符串必须是第二个参数。

add a note

User Contributed Notes

There are no user contributed notes for this page.
To Top