首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用Node.js加密创建HMAC-SHA1哈希?

如何使用Node.js加密创建HMAC-SHA1哈希?
EN

Stack Overflow用户
提问于 2011-09-20 12:29:53
回答 4查看 133.7K关注 0票数 222

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

如何使用Node.js Crypto创建散列?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2011-09-20 12:38:22

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

代码语言:javascript
复制
const crypto = require('crypto')

const text = 'I love cupcakes'
const key = 'abcdeg'

crypto.createHmac('sha1', key)
  .update(text)
  .digest('hex')
票数 398
EN

Stack Overflow用户

发布于 2013-09-15 22:59:45

几年前,有人说update()digest()是遗留方法,并引入了新的streaming API方法。现在,文档上说这两种方法都可以使用。例如:

代码语言:javascript
复制
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);

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

参见https://nodejs.org/api/crypto.html#crypto_class_hmac。提供了更多使用流方法的示例。

票数 100
EN

Stack Overflow用户

发布于 2014-10-09 23:04:39

Gwerder的解决方案不起作用,因为hash = hmac.read();发生在流完成之前。因此,AngraX的问题。在本例中,hmac.write语句也是不必要的。

取而代之的是:

代码语言:javascript
复制
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...
});

更正式地说,如果你愿意,这句话

代码语言:javascript
复制
hmac.end(text, function () {

可能会被写入

代码语言:javascript
复制
hmac.end(text, 'utf8', function () {

因为在本例中文本是utf字符串

票数 22
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7480158

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档