以下是PHP 7.4版本的实现,使用了相同的依赖库apache/commons-codec
来进行十六进制编码。
<?php
use function Sodium\crypto_generichash;
use function Sodium\crypto_pwhash_str;
use function Sodium\crypto_pwhash_str_verify;
require_once __DIR__ . '/vendor/autoload.php';
function hmacsha256($plainStr, $key)
{
$secretKey = new \SecretKeySpec(
utf8_encode($key),
'HmacSHA256'
);
$mac = hash_init('sha256', HASH_HMAC, $secretKey);
hash_update($mac, utf8_encode($plainStr));
$digest = hash_final($mac, true);
return byte2HexStr($digest);
}
function byte2HexStr($array)
{
return $array !== null ? \strval(Hex::encode($array)) : null;
}
function generate_password($password, $salt)
{
return crypto_pwhash_str($password, \SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE, \SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE);
}
function verify_password($hash, $password)
{
return crypto_pwhash_str_verify($hash, $password);
}