简体   繁体   中英

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

Golang code is as below

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

How can I convert from this to reactjs code. I am trying like this

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

but result is not same with golang result. What am I wrong? and How will I do?

Go code: https://play.golang.org/p/7pXgn5GPQm

React:

  • Package used: "crypto-js": "^3.1.9-1"
  • React v15.4.2

Inside a React Component, a function:

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

Inside render()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM