如何在Node.js中使用Hmac创建令牌

huangapple go评论66阅读模式
英文:

How to create token using Hmac in Node js

问题

const crypto = require('crypto');
const mysecret = 'your_secret_key'; // Replace with your secret key
const texttoEncode = 'text_to_encode'; // Replace with the text you want to encode

const hmac = crypto.createHmac('sha256', mysecret);
const hash = hmac.update(texttoEncode, 'utf-8').digest('hex');
英文:

I am trying to convert Java code to Node js to generate token using Hmac.
Java code-

Mac mac = Mac.getInstance("HmacSHA256")
SecretKeySpec key = new SecretKeySpec(mysecret.getBytes("UTF-8","HmacSHA256")
mac.init(key)
byte[] hash = mac.doFinal(texttoEncode.getBytes(UTF-8))

Can anyone please suggest what will be its Javascript /node js equivalent.

答案1

得分: 3

The crypto内置模块提供了以下签名的 createHmac 方法:

crypto.createHmac(algorithm, key[, options])

要创建一个令牌:

const Crypto = require('crypto');

const token = Crypto.createHmac('sha256', 'a secret').update('data').digest('hex');

console.log(token); // 5da263f0f0ee86707c7c3f590d20066b7107e5ac70a41560926fa634bc78b137
英文:

The crypto built-in module provides createHmac method with the following signature:

crypto.createHmac(algorithm, key[, options])

To create a token:

const Crypto = require('crypto');

const token = Crypto.createHmac('sha256', 'a secret').update('data').digest('hex');

console.log(token); // 5da263f0f0ee86707c7c3f590d20066b7107e5ac70a41560926fa634bc78b137

huangapple
  • 本文由 发表于 2020年7月31日 17:21:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/63189099.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定