php擴充hash模組基本上使用的範例程式碼

黄舟
發布: 2023-03-06 16:22:02
原創
1398 人瀏覽過

php擴充hash模組基本上使用的範例程式碼

<?php
echo &#39;<pre class="brush:php;toolbar:false">&#39;;

$algos = hash_algos(); //列出所有支持的hash算法
// print_r($algos);


// ------------------------------------------------------
// 字符串hash
$data = &#39;The quick brown fox jumped over the lazy dog.&#39;;
echo hash(&#39;md5&#39;, $data); //md5 哈希
$key = &#39;md5-key&#39;;
echo hash_hmac(&#39;md5&#39;, $data, $key); //使用 HMAC 方法生成带有密钥的哈希值


// ------------------------------------------------------
// 文件hash
$file = &#39;hmac.txt&#39;;
echo hash_file(&#39;md5&#39;, $file);
echo hash_hmac_file(&#39;md5&#39;, $file, $key);


// ------------------------------------------------------
/**
 * @param $algo hash算法
 * @param $data string|array 字符串或者字符串数组
 * @param $options 进行哈希运算的可选设置,目前仅支持:HASH_HMAC。当指定此选项时,必须指定 key 参数
 * @param $key 当 options 参数为 HASH_HMAC 时,使用此参数传入进行 HMAC 哈希运算时的共享密钥
 */
function my_hash_data($algo, $data, $options = 0, $key = NULL) {
	// resource hash_init ( string $algo [, int $options = 0 [, string $key = NULL ]] )
	$ctx = hash_init($algo, $options, $key);
	if(is_string($data)) {
		hash_update($ctx, $data);
	} else if(is_array($data)) {
		foreach($data as $s) {
			hash_update($ctx, $s); //填充数据, 可以多次调用, 和拼接字符串效果一样
		}
	}
	return hash_final($ctx); //输出最后的数据
}

// test code
echo my_hash_data(&#39;md5&#39;, $data);


// ------------------------------------------------------
/**
 * 文件类型 hash
 */
function my_hash_file($algo, $filename, $options = 0, $key = NULL) {
	$ctx = hash_init($algo, $options, $key);
	/*
	两个函数的不同之处:
	 1. hash_update_stream	第二个参数是一个打开的文件句柄
	 2. hash_update_file	第二个参数是一个文件名
	*/
	hash_update_file($ctx, $filename);
	return hash_final($ctx);
}

// test code
echo my_hash_file(&#39;sha1&#39;, $file);
登入後複製

以上是php擴充hash模組基本上使用的範例程式碼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!