= 5.1.2, PHP 7, PHP 8, PECL hash >= 1.1)hash — 生成哈希值 (消息摘要)說明hash(string $algo, string $data, bool $raw_output = false): string參數(shù)algo要使用的哈">

hash

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL hash >= 1.1)

hash生成哈希值 (消息摘要)

說明

hash(string $algo, string $data, bool $raw_output = false): string

參數(shù)

algo

要使用的哈希算法,例如:"md5","sha256","haval160,4" 等。 在 hash_algos() 中查看支持的算法。

data

要進行哈希運算的消息。

raw_output

設(shè)置為 true 輸出原始二進制數(shù)據(jù), 設(shè)置為 false 輸出小寫 16 進制字符串。

返回值

如果 raw_output 設(shè)置為 true, 則返回原始二進制數(shù)據(jù)表示的信息摘要, 否則返回 16 進制小寫字符串格式表示的信息摘要。

范例

示例 #1 一個 hash() 例程

<?php
echo hash('ripemd160''The quick brown fox jumped over the lazy dog.');
?>

以上例程會輸出:

ec457d0a974c48d5685a7efa03d137dc8bbde7e3

示例 #2 使用 PHP 5.4 或者更高版本計算 tiger 哈希值

<?php
function old_tiger($data ""$width=192$rounds 3) {
    return 
substr(
        
implode(
            
array_map(
                function (
$h) {
                    return 
str_pad(bin2hex(strrev($h)), 16"0");
                },
                
str_split(hash("tiger192,$rounds"$datatrue), 8)
            )
        ),
        
048-(192-$width)/4
    
);
}
echo 
hash('tiger192,3''a-string'), PHP_EOL;
echo 
old_tiger('a-string'), PHP_EOL;
?>

以上例程在 PHP 5.3 中的輸出:

146a7492719b3564094efe7abbd40a7416fd900179d02773
64359b7192746a14740ad4bb7afe4e097327d0790190fd16

以上例程在 PHP 5.4 中的輸出:

64359b7192746a14740ad4bb7afe4e097327d0790190fd16
146a7492719b3564094efe7abbd40a7416fd900179d02773

參見

  • hash_file() - 給指定文件的內(nèi)容生成哈希值
  • hash_hmac() - 使用 HMAC 方法生成帶有密鑰的哈希值
  • hash_init() - 初始化增量哈希運算上下文
  • md5() - 計算字符串的 MD5 散列值
  • sha1() - 計算字符串的 sha1 散列值