dtc88867 2017-01-07 12:04
浏览 337
已采纳

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

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条回答 默认 最新

  • duanliujie8639 2017-01-10 01:12
    关注

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题