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

1.2k Views Asked by At

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?

1

There are 1 best solutions below

0
On BEST ANSWER

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