PHP - hash_init() 函式



定義和用法

hash_init() 函式初始化一個可用於其他雜湊函式(如 hash_update()、hash_final() 等)的增量雜湊上下文。它以雜湊演算法作為輸入,以雜湊上下文作為輸出。

雜湊上下文是根據 hash_init() 內部使用的 hash_algo 生成的。您可以使用 hash_update() 函式使用雜湊上下文更新您的資料或訊息,並使用 hash_final() 獲取最終的雜湊值。

語法

hash_init ( string $algo [, int $options = 0 [, string $key = NULL ]] ) : HashContext

引數

序號 引數和說明
1

algo

雜湊演算法的名稱。雜湊提供了大量的演算法列表,其中一些重要的演算法是 md5、sha256 等。

要獲取支援的完整演算法列表,請使用雜湊函式 hash_algos()

2

options

僅支援一個選項,即 HASH_HMAC。如果您使用選項,則金鑰也必須是強制性的。

3

key

如果將 HASH_HMAC 用作選項,則還必須提供金鑰,它將是與 HMAC 雜湊方法一起使用的共享金鑰。

返回值

PHP hash_init() 函式返回一個雜湊上下文。雜湊上下文可用於其他雜湊函式,如 hash_update()、hash_update_stream()、hash_update_file() 和 hash_final()。

PHP 版本

此函式將在 PHP 版本大於 5.1.2 的版本中執行。

示例 1

生成雜湊上下文 -

<?php
   $hash_context = hash_init('md5');
   hash_update($hash_context, 'Testing php');
   hash_update($hash_context, ' hash functions.');
   echo hash_final($hash_context);
?>

輸出

這將產生以下結果 -

e4310012c89a4b8479fd83694a2a3a31

示例 2

將 hash_init() 與 hash_copy() 一起使用 -

<?php
   $hash_context = hash_init("md5");
   hash_update($hash_context, "Welcome To Tutorialspoint");
   $hash_copy= hash_copy($hash_context);
   echo hash_final($hash_context);
   echo "<br/>";
   hash_update($hash_copy,  "Welcome To Tutorialspoint");
   echo hash_final($hash_copy);
?>

這將產生以下結果 -

6211420491a571f89f970683221d4480<br/>d0b25da996bf035057aba79082c53b30
php_function_reference.htm
廣告