有没有办法从 PHP 生成与 nodejs 相同的 Hmac 哈希输出?

Is there a way to generate same Hmac hash output from PHP as done with nodejs?

以下是我的 nodejs 创建 HMAC 散列的函数 -

function hash() {
    key = "hello";
    msg = "Hello";
    var hmac = crypto.createHmac('sha256', key);
    hmac.update(msg, 'utf8');
    var digest = hmac.digest();
    console.log('---hash =======>' + digest);
    return digest;
}

function hmacHex(key, msg) {
    var hmac = crypto.createHmac('sha256', key);
    hmac.update(msg, 'utf8');
    var digest = hmac.digest('hex');
    console.log('---hmacHex ====>' + digest);
    return digest;
}

var res = hash();
hmacHex("hello", res);

OUTPUT FROM hash() => }/�(K=�����('�Zt�h�\D�Z��@ywڦ�

OUTPUT FROM hmaxHex() => 692a18bd347476d28300e579794ba799cda80625191ef71783fce95692c2b6f9

以下是我的 PHP 生成上述输出的等效代码 -

class Signature{

public function hash()
    {
        $key = "hello";
        $msg = "Hello";
        $hash = hash_hmac('sha256', utf8_encode($msg), $key, true);
        error_log('---hash ===>'.$hash);
        return $hash;
    }

public function hmacHex($msg)
    {
        $key = "hello";
        $hash = hash_hmac('sha256', utf8_encode($msg), $key, false);
        error_log('---hmacHex ===>' . $hash);
        return $hash;
    }
}

$obj = new Signature();

$res = $obj->hash();
$obj->hmacHex($res);
OUTPUT FROM hash() => }/?(K=?????('?Zt?h?\D?Z??@ywڦ?

OUTPUT FROM hmacHex => d920859abc579a070f2f8177e71d8431955784c8ed1d596b3364871ba35b5951

从输出中可以清楚地看出,在 nodejs 中我得到了替换字符,而在 PHP 中它显示为问号。

我正在尝试从我的 PHP 代码生成完全相同的输出,以便在重新散列输出时它应该是相同的。

我会更新我的答案以反映您的代码更改。感谢@Topaco 解决了这个问题。

php

class Signature {

    public function hash()
    {
        $key = "hello";
        $msg = "Hello";
        $hash = hash_hmac('sha256', $msg, $key, true);
        error_log('---hash ===>'.$hash);
        return $hash;
    }

    public function hmacHex($msg)
    {
        $key = "hello";
        $hash = hash_hmac('sha256', $msg, $key, false);
        error_log('---hmacHex ===>' . $hash);
        return $hash;
    }
}

$obj = new Signature();

$res = $obj->hash();
$obj->hmacHex($res);

节点

class Signature {

    public function hash()
    {
        $key = "hello";
        $msg = "Hello";
        $hash = hash_hmac('sha256', $msg, $key, true);
        error_log('---hash ===>'.$hash);
        return $hash;
    }

    public function hmacHex($msg)
    {
        $key = "hello";
        $hash = hash_hmac('sha256', $msg, $key, false);
        error_log('---hmacHex ===>' . $hash);
        return $hash;
    }
}

$obj = new Signature();

$res = $obj->hash();
$obj->hmacHex($res);

php 输出:

---hash ===>}/(K=('Zth\DZ@ywڦ
---hmacHex ===>692a18bd347476d28300e579794ba799cda80625191ef71783fce95692c2b6f9

Node.js 输出:

---hash =======>}/�(K=�����('�Zt�h�\D�Z��@ywڦ�
---hmacHex ====>692a18bd347476d28300e579794ba799cda80625191ef71783fce95692c2b6f9

你的$keyphp端必须是utf8_encode因为在节点端crypto.createHmac('sha256', key);

这里的key是crypto.createHmac.

编码的utf8