查詢

sodium_compare()函式—用法及示例

「 比較兩個字串是否相等,可以防止時間側通道攻擊 」


函式名稱:sodium_compare()

適用版本:PHP 7.2.0及以上

函式描述:sodium_compare()函式用於比較兩個字串是否相等,可以防止時間側通道攻擊。

用法:

int sodium_compare(string $string1, string $string2): int

引數:

  • $string1:要比較的第一個字串。
  • $string2:要比較的第二個字串。

返回值:

  • 如果兩個字串相等,則返回0。
  • 如果兩個字串不相等,則返回一個非零整數。

示例:

$hash1 = sodium_crypto_generichash('Hello World', '');
$hash2 = sodium_crypto_generichash('hello world', '');

$result = sodium_compare($hash1, $hash2);

if ($result === 0) {
    echo "字串相等";
} else {
    echo "字串不相等";
}

以上示例中,我們使用sodium_crypto_generichash()函式生成兩個不同的雜湊值,然後使用sodium_compare()函式比較這兩個雜湊值。如果兩個雜湊值相等,將輸出"字串相等";否則,將輸出"字串不相等"。

注意:為了正確使用sodium_compare()函式,確保在PHP安裝時已啟用libsodium擴充套件。

補充糾錯
上一個函式: sodium_base642bin()函式
下一個函式: sodium_add()函式
熱門PHP函式
分享連結