在 php 中,使用 hash_hmac() 函數(shù)結(jié)合 sha256 算法來(lái)創(chuàng)建簽名是一種常見(jiàn)的安全實(shí)踐。這種方法可以幫助在數(shù)據(jù)傳輸過(guò)程中驗(yàn)證數(shù)據(jù)的完整性和真實(shí)性,防止數(shù)據(jù)被篡改或偽造。通過(guò)結(jié)合 hash_hmac() 和 sha256,可以生成一個(gè)基于密鑰的安全哈希值,確保數(shù)據(jù)的安全傳輸和處理。在本文中,我們將深入探討如何在 php 中使用 hash_hmac() 和 sha256 來(lái)創(chuàng)建簽名,以及如何應(yīng)用這種方法來(lái)增強(qiáng)數(shù)據(jù)安全性。
我們將向你展示如何使用 hash_hmac 和 sha256 加密器來(lái)創(chuàng)建安全簽名,你可以將其存儲(chǔ)在數(shù)據(jù)庫(kù)中或在你的登錄表單中使用。
php 中的 hash_hmac() 函數(shù)
hash_hmac() 創(chuàng)建一個(gè)字母數(shù)字鍵控的秘密哈希值。它利用稱為 HMAC 方法的加密身份驗(yàn)證技術(shù)。
語(yǔ)法:
hash_hmac($alGo, $data, $key, $binary = false);
登錄后復(fù)制
$algo 是 hash_hmac 參數(shù)之一,用作簽名秘密鍵控哈希值 (String)。
$data,一個(gè)散列值(通常是用戶的密碼)。它可以是字母數(shù)字。
$key 是從 HMAC 方法生成的,它是你從函數(shù)中獲得的密鑰,以及其他編程用途。
最后一個(gè)參數(shù) $binary 是二進(jìn)制值。
它在 TRUE 時(shí)返回原始數(shù)據(jù),并在 FALSE 時(shí)拋出小寫(xiě)十六進(jìn)制。
在 PHP 中使用 hash_hmac() 和 sha256
例子:
<?php
//sha256 is a $algo
$PassWord= 'ThisIS123PasswORD' ; //data
$secret ="ABCabc"; //$key
//false is bool value to check whether the method works or not
$hash_it = hash_hmac("sha256", utf8_encode($Password), $secret, false);//all four parameters
if(!$hash_it){ //checks true or false
echo "Password was not encrypted!";
}
echo "Your encrypted signature is:<b> '.$hash_it.' </b>";
?>
登錄后復(fù)制
輸出:
Your encrypted signature is: '.46e9757dc98f478c28f035cfa871dbd19b5a2bf8273225191bcca78801304813
登錄后復(fù)制
使用 hash_hmac() 和 base64_encode()
如果你希望你的加密簽名更安全,你還可以執(zhí)行以下代碼片段。
例子:
<?php
$my_sign = "abc123";
$key = TRUE;
$base64_encode = base64_encode(hash_hmac('sha256', $my_sign, $key, true));
if(!$base64_encode){
echo "Your signature with the base64_decode(hash_hmac()); failed";
}
else{
echo "Your base64_decode(hash_hmac()); encrypted signature is is:<b> $base64_encode.' </b>";
}
?>
登錄后復(fù)制
輸出:
Your base64_decode(hash_hmac()); encrypted signature is is: '.00g0QMQlnluXxijqot60WZf6InDi07b/Mb5lL7eVZ34
登錄后復(fù)制
在 PHP 中使用 hash_hmac() 和 sha256 并應(yīng)用 hex2bin/bin2hex 轉(zhuǎn)換
hex2bin() – 此函數(shù)解碼已以十六進(jìn)制編碼的二進(jìn)制字符串。
bin2hex() – 使用 bin2hex() 方法將 ASCII 字符串轉(zhuǎn)換為十六進(jìn)制值。
假設(shè)你有要加密的關(guān)鍵財(cái)務(wù)數(shù)據(jù)并為用戶創(chuàng)建密鑰。
例子:
<?php
$createhashmackey = "2974924872949278487322348237749823";
$bank_acc = "029480247299262947328749287";
$current_bal = $sum * 10000 / 450;
$bank_locker_no = 'AC54-A76X';
$last_deposit= $when;
$se = hex2bin($createhashmackey);
$create_his_signature = $bank_acc . $current_bal. $bank_locker_no . $last_deposit;
$enigma = bin2hex(hash_hmac('sha256', $create_his_signature, $se));
echo "The secret signature is.$enigma.";
登錄后復(fù)制
輸出:
The secret signature is.33633066323533383537663538323937373536393764396530343661663336666438636435363631383934363864383966316133633433633965343234336233.
登錄后復(fù)制
這是本文中所有代碼示例的輸出。






