HOWTO · PHP

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

我們將建立基於字串的金鑰並將它們轉換為祕密簽名,我們將使用 hash_hmac() 方法和一些最常見的 HMAC 方法進行密碼轉換。我們還將使用 PHP 中的 sha256 和 hex2bin 和 bin2hex 函式建立一個複雜的簽名。

本頁內容

PHP 具有用於資料安全的最佳加密功能之一。Hash_hmac() 加密函式是最著名的加密器之一。

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

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= '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>";
?>

輸出:

Your encrypted signature is: '.46e9757dc98f478c28f035cfa871dbd19b5a2bf8273225191bcca78801304813

使用 hash_hmac() 和 base64_encode()

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

例子:

<?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>";
}
?>

輸出:

Your base64_decode(hash_hmac()); encrypted signature is is: '.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   = '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.";

輸出:

The secret signature is.33633066323533383537663538323937373536393764396530343661663336666438636435363631383934363864383966316133633433633965343234336233.

這是本教程中所有程式碼示例的輸出。

php 中 hash_hmac() 和 sha256 的簽名