如何使用Node.js Crypto创建HMAC-SHA1哈希?

use*_*495 190 javascript algorithm hash node.js node-crypto

我想创建一个哈希I love cupcakes(用密钥签名abcdeg)

如何使用Node.js加密创建该哈希?

Ric*_*asi 348

加密文档:http://nodejs.org/api/crypto.html

var crypto = require('crypto')
  , text = 'I love cupcakes'
  , key = 'abcdeg'
  , hash

hash = crypto.createHmac('sha1', key).update(text).digest('hex')
Run Code Online (Sandbox Code Playgroud)

  • 要验证哈希,您应该使用`crypto.timingSafeEqual(Buffer.from(a),Buffer.from(b))`:/sf/ask/2176713381/一个安全的比较和一个简单的/ 31096242#comment97670146_31096242 (2认同)

Ada*_*ths 95

几年前,有人说update()digest()人的传统方法,并引入了新的流API的方法.现在文档说可以使用任何一种方法.例如:

var crypto    = require('crypto');
var text      = 'I love cupcakes';
var secret    = 'abcdeg'; //make this your secret!!
var algorithm = 'sha1';   //consider using sha256
var hash, hmac;

// Method 1 - Writing to a stream
hmac = crypto.createHmac(algorithm, secret);    
hmac.write(text); // write in to the stream
hmac.end();       // can't read from the stream until you call end()
hash = hmac.read().toString('hex');    // read out hmac digest
console.log("Method 1: ", hash);

// Method 2 - Using update and digest:
hmac = crypto.createHmac(algorithm, secret);
hmac.update(text);
hash = hmac.digest('hex');
console.log("Method 2: ", hash);
Run Code Online (Sandbox Code Playgroud)

在节点v6.2.2和v7.7.2上测试

请参阅https://nodejs.org/api/crypto.html#crypto_class_hmac.给出了使用流式方法的更多示例.

  • 截至2016年11月,`digest`和`update`已被弃用,并且在文档中有特色:https://nodejs.org/api/crypto.html#crypto_class_hmac.我建议仅在您从流中读取时才使用流API. (5认同)
  • 在我的生活中,我不能做这项工作.hmac.read()返回一个"[object SlowBuffer]",如果我尝试使用hmac.read().toString('hex')读取内容; 我没有得到预期的价值.如果我使用更新/摘要弃用方法,它将返回预期的字符串.我正在使用它来验证从第三方POST到我的服务器的签名.有什么想法发生了什么? (2认同)

Dav*_*ave 21

Gwerder的解决方案无法工作,因为hash = hmac.read();在流完成之前就已经发生了.因此AngraX的问题.hmac.write此示例中的声明也是不必要的.

而是这样做:

var crypto    = require('crypto');
var hmac;
var algorithm = 'sha1';
var key       = 'abcdeg';
var text      = 'I love cupcakes';
var hash;

hmac = crypto.createHmac(algorithm, key);

// readout format:
hmac.setEncoding('hex');
//or also commonly: hmac.setEncoding('base64');

// callback is attached as listener to stream's finish event:
hmac.end(text, function () {
    hash = hmac.read();
    //...do something with the hash...
});
Run Code Online (Sandbox Code Playgroud)

更正式的,如果你愿意,行

hmac.end(text, function () {
Run Code Online (Sandbox Code Playgroud)

可以写

hmac.end(text, 'utf8', function () {
Run Code Online (Sandbox Code Playgroud)

因为在这个例子中,text是一个utf字符串