簡體   English   中英

如何將此代碼從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”
  • 反應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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM