在 NodeJS 加密中使用 SHA-256
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27970431/
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
Using SHA-256 with NodeJS Crypto
提问by Cameron
I'm trying to hash a variable in NodeJS like so:
我正在尝试在 NodeJS 中散列一个变量,如下所示:
var crypto = require('crypto');
var hash = crypto.createHash('sha256');
var code = 'bacon';
code = hash.update(code);
code = hash.digest(code);
console.log(code);
But looks like I have misunderstood the docs as the console.log doesn't log a hashed version of bacon but just some information about SlowBuffer.
但看起来我误解了文档,因为 console.log 没有记录培根的散列版本,而只是关于 SlowBuffer 的一些信息。
What's the correct way to do this?
这样做的正确方法是什么?
回答by MaximeF
base64:
base64:
const hash = crypto.createHash('sha256').update(pwd).digest('base64');
hex:
十六进制:
crypto.createHash('sha256').update(pwd).digest('hex');
回答by Blaskovicz
Similar to the answers above, but this shows how to do multiple writes; for example if you read line-by-line from a file and then add each line to the hash computation as a separate operation.
类似于上面的答案,但这显示了如何进行多次写入;例如,如果您从文件中逐行读取,然后将每一行作为单独的操作添加到哈希计算中。
In my example, I also trim newlines / skip empty lines (optional):
在我的示例中,我还修剪换行符/跳过空行(可选):
const {createHash} = require('crypto');
// lines: array of strings
function computeSHA256(lines) {
const hash = createHash('sha256');
for (let i = 0; i < lines.length; i++) {
const line = lines[i].trim(); // remove leading/trailing whitespace
if (line === '') continue; // skip empty lines
hash.write(line); // write a single line to the buffer
}
return hash.digest('base64'); // returns hash as string
}
I use this code ensure generated lines of a file aren't edited by someone manually. To do this, I write the lines out, append a line like sha256:<hash>with the sha265-sum, and then, upon next run, verify the hash of those lines matches said sha265-sum.
我使用此代码确保文件的生成行不会被某人手动编辑。为此,我将这些行写出来,添加类似sha256:<hash>sha265-sum 的行,然后在下次运行时验证这些行的散列是否与 sha265-sum 匹配。
回答by Mohamed.Abdo
const crypto = require('crypto');
const hash = crypto.createHash('sha256');
hash.on('readable', () => {
const data = hash.read();
if (data) {
console.log(data.toString('hex'));
// Prints:
// 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50
}
});
hash.write('some data to hash');
hash.end();

