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

时间:2017-01-07 12:04:34

标签: javascript go cryptojs

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结果不一样。我错了什么?我该怎么办?

1 个答案:

答案 0 :(得分:0)

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

阵营:

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

在React Component内部,有一个函数:

    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))
  }

内部渲染()

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