Javascript 如何使用 Node.js Crypto 创建 HMAC-SHA1 哈希?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7480158/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I use Node.js Crypto to create a HMAC-SHA1 hash?
提问by user847495
I want to create a hash of I love cupcakes
(signed with the key abcdeg
)
我想创建一个I love cupcakes
(用密钥签名abcdeg
)的散列
How can I create that hash, using Node.js Crypto?
如何使用 Node.js Crypto 创建该哈希?
回答by Ricardo Tomasi
Documentation for crypto: http://nodejs.org/api/crypto.html
加密文档:http: //nodejs.org/api/crypto.html
const crypto = require('crypto')
const text = 'I love cupcakes'
const key = 'abcdeg'
crypto.createHmac('sha1', key)
.update(text)
.digest('hex')
回答by Adam Griffiths
A few years ago it was said that update()
and digest()
were legacy methods and the new streaming API approach was introduced. Now the docs say that either method can be used. For example:
几年前,有人说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);
Tested on node v6.2.2 and v7.7.2
在节点 v6.2.2 和 v7.7.2 上测试
See https://nodejs.org/api/crypto.html#crypto_class_hmac. Gives more examples for using the streaming approach.
请参阅https://nodejs.org/api/crypto.html#crypto_class_hmac。提供了更多使用流方法的示例。
回答by Dave
Gwerder's solution wont work because hash = hmac.read();
happens before the stream is done being finalized. Thus AngraX's issues. Also the hmac.write
statement is un-necessary in this example.
Gwerder 的解决方案不起作用,因为hash = hmac.read();
在流完成之前发生。因此 AngraX 的问题。hmac.write
在此示例中,该语句也是不必要的。
Instead do this:
而是这样做:
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...
});
More formally, if you wish, the line
更正式的,如果你愿意,这条线
hmac.end(text, function () {
could be written
可以写
hmac.end(text, 'utf8', function () {
because in this example text is a utf string
因为在这个例子中 text 是一个 utf 字符串