返回顶部
首页 > 资讯 > 后端开发 > PHP编程 >在 PHP 中从 Hash_hmac() 和 Sha256 创建签名
  • 362
分享到

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

2024-02-27 21:02:23 362人浏览 泡泡鱼
摘要

PHP 具有用于数据安全的最佳加密功能之一。Hash_hMac() 加密函数是最著名的加密器之一。 我们将向你展示如何使用 hash_hmac 和 sha256 加密器来创建安全签名,你可以将其存储

PHP 具有用于数据安全的最佳加密功能之一。Hash_hMac() 加密函数是最著名的加密器之一。

我们将向你展示如何使用 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= '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 的签名

--结束END--

本文标题: 在 PHP 中从 Hash_hmac() 和 Sha256 创建签名

本文链接: https://www.lsjlt.com/news/569187.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作