首頁  >  文章  >  後端開發  >  在 PHP 中從 Hash_hmac() 和 Sha256 建立簽名

在 PHP 中從 Hash_hmac() 和 Sha256 建立簽名

王林
王林轉載
2024-02-29 14:34:24666瀏覽

在 PHP 中,使用 Hash_hmac() 函數結合 Sha256 演算法來建立簽章是一種常見的安全實務。這種方法可以幫助在資料傳輸過程中驗證資料的完整性和真實性,防止資料被竄改或偽造。透過結合 Hash_hmac() 和 Sha256,可以產生一個基於金鑰的安全雜湊值,確保資料的安全傳輸和處理。在本文中,我們將深入探討如何在 PHP 中使用 Hash_hmac() 和 Sha256 來建立簽名,以及如何應用此方法來增強資料安全性。

我們將向你展示如何使用hash_hmacsha256 加密器來建立安全簽章,你可以將其儲存在資料庫或在你的登入表單中使用。


php 中的 hash_hmac() 函數

hash_hmac() 建立一個字母數字鍵控的秘密雜湊值。它利用稱為 HMAC 方法的加密驗證技術。

文法:

hash_hmac($alGo, $data, $key, $binary = false);
  1. $algo 是 hash_hmac 參數之一,用作簽章秘密鍵控雜湊值 (String)。
  2. $data,一個雜湊值(通常是使用者的密碼)。它可以是字母數字。
  3. $key 是從 HMAC 方法產生的,它是你從函數中獲得的金鑰,以及其他程式設計用途。
  4. 最後一個參數 $binary 是二進位值。

它在 TRUE 時傳回原始數據,並在 FALSE 時拋出小寫十六進位。


在 PHP 中使用 hash_hmac()sha256

# 範例:

<?php
//sha256 is a $algo
$PassWord= &#39;ThisIS123PasswORD&#39; ; //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> &#39;.$hash_it.&#39; </b>";
?>

輸出:

Your encrypted signature is: &#39;.46e9757dc98f478c28f035cfa871dbd19b5a2bf8273225191bcca78801304813

使用 hash_hmac()base64_encode()

# 如果你希望你的加密簽章更安全,你也可以執行以下程式碼片段。

範例:

<?php
$my_sign = "abc123";
$key = TRUE;
 $base64_encode = base64_encode(hash_hmac(&#39;sha256&#39;, $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.&#39; </b>";
}
?>

輸出:

Your base64_decode(hash_hmac()); encrypted signature is is: &#39;.00g0QMQlnluXxijqot60WZf6InDi07b/Mb5lL7eVZ34

在 PHP 中使用 hash_hmac()sha256 並套用 hex2bin/bin2hex 轉換

  • hex2bin() - 此函數解碼已以十六進位編碼的二進位字串
  • bin2hex() - 使用 bin2hex() 方法將 ASCII 字串轉換為十六進位值。

假設你有要加密的關鍵財務資料並為使用者建立金鑰。

範例:

<?php
$createhashmackey = "2974924872949278487322348237749823";
$bank_acc = "029480247299262947328749287";
$current_bal = $sum * 10000 / 450;
$bank_locker_no = &#39;AC54-A76X&#39;;
$last_deposit= $when;
$se = hex2bi&#110;($createhashmackey);
$create_his_signature = $bank_acc . $current_bal. $bank_locker_no . $last_deposit;
$enigma = bin2he&#120;(hash_hmac(&#39;sha256&#39;, $create_his_signature, $se));
echo "The secret signature is.$enigma.";

輸出:

The secret signature is.33633066323533383537663538323937373536393764396530343661663336666438636435363631383934363864383966316133633433633965343234336233.

這是本文中所有程式碼範例的輸出。

在 PHP 中从 Hash_hmac() 和 Sha256 创建签名

以上是在 PHP 中從 Hash_hmac() 和 Sha256 建立簽名的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:lsjlt.com。如有侵權,請聯絡admin@php.cn刪除