PHP - Hash hmac_file() 函式



定義和用法

hash_hmac_file() 函式用於使用 HMAC 方法為給定檔案內容生成帶金鑰的雜湊值。

HMAC 代表帶金鑰的雜湊訊息認證碼或基於雜湊的訊息認證碼。它利用 md5、sha-256 等加密雜湊函式和一個金鑰來對給定的檔案內容進行雜湊。

語法

hash_hmac_file ( 
   string $algo , string $filename , string $key [, bool $raw_output = FALSE ] 
) 
: string

引數

序號 引數及描述
1

algo

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

要獲取支援的完整演算法列表,請檢視 hash_hmac_algos()。

2

filename

獲取檔案內容的檔案路徑。

3

key

生成訊息摘要的 HMAC 變體的金鑰。

4

raw_output

預設值為 false,因此它返回小寫十六進位制值。如果值為 true,它將返回原始二進位制資料。

返回值

hash_hmac_file() 函式返回一個計算出的訊息摘要字串,如果 raw_output 為 false,則該字串將以小寫十六進位制值的格式顯示,否則它將返回原始二進位制資料。

PHP 版本

此函式將在 PHP 5.1.2 或更高版本中執行。

示例 1

使用 hash_hmac_file() -

<?php
   file_put_contents('file2.txt', 'Welcome to Tutorialspoint');
   echo hash_hmac_file('md5', 'file2.txt', 'anysecretkey');
?>

輸出

這將產生以下結果 -

e519cec21ac0c04a92ff5b358931b49d

示例 2

檔案內容更改時 hash_hmac_file() 輸出的差異 -

<?php
   file_put_contents('abc.txt', 'Hello'); 
   echo hash_hmac_file('sha256', 'abc.txt', 'mysecretkey'); 
   echo "<br/><br/>";
   file_put_contents('abc.txt', 'World');
   echo hash_hmac_file('md5', 'abc.txt', 'anysecretkey'); 
?>

輸出

這將產生以下結果 -

362a60a6ef4e35f9559304a6b5372b070c97ba33cb4a747503c9c58b5c85e6db2652fb7ccf4cff91df4f08add44b93b2

示例 3

hash_file() 和 hash_hmac_file() 輸出的差異 -

<?php
   file_put_contents('filetest.txt', 'Welcome to Tutorialspoint');
   echo hash_file('sha256', 'filetest.txt');
   echo "<br/><br/>";
   file_put_contents('abc.txt', 'Welcome to Tutorialspoint'); 
   echo hash_hmac_file('sha256', 'abc.txt', 'mysecretkey'); 
?>

輸出

這將產生以下結果 -

a6baf12546b9a5cf6df9e22ae1ae310b8c56be2da2e9fd2c91c94314eb0e5a2e7f8a726d250c08400820b3a1818f5b650784990eee7f23e3f1946373f2dd6e96
php_function_reference.htm
廣告