如何将此代码从 golang 转换为 crypto hmac sha256 hex 中的 reactjs

How can convert this code from golang to reactjs in crypto hmac sha256 hex

Golang代码如下

func GenerateClientToken(secret, user, timestamp, info string) string {
    token := hmac.New(sha256.New, []byte(secret))
    token.Write([]byte(user))
    token.Write([]byte(timestamp))
    token.Write([]byte(info))
    return hex.EncodeToString(token.Sum(nil))
}

我如何将其转换为 reactjs 代码。 我正在尝试这样

import CryptoJS from 'crypto-js'

generateClientToken(secret, user, timestamp, info) {
        var hmac = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, secret);

        hmac.update(user);
        hmac.update(timestamp);
        hmac.update(info);

        var hash = hmac.finalize();
        console.log("hmac: ", hash.toString(CryptoJS.enc.Base64))
        console.log("hmac: ", hash.toString(CryptoJS.enc.Hex))
    }

但结果与 golang 结果不同。我错了什么?我该怎么做?

转到代码:https://play.golang.org/p/7pXgn5GPQm

反应:

  • 使用的包:"crypto-js":“^3.1.9-1”
  • React v15.4.2

在 React 组件中,一个函数:

    generateClientToken(secret, user, timestamp, info) {
      let hmac = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, secret);

      hmac.update(user);
      hmac.update(timestamp);
      hmac.update(info);

      let hash = hmac.finalize();

      console.log("hmac: ", hash.toString(CryptoJS.enc.Hex))
  }

在 render() 内部

const secret = "test";
const user = "Dennis";
const timestamp = "1";
const info = "qwerty";
this.generateClientToken(secret, user, timestamp, info);