将SHA-256与NodeJS加密一起使用

时间:2015-01-15 18:26:16

标签: node.js node-crypto

我试图在NodeJS中散列变量,如下所示:

var crypto = require('crypto');

var hash = crypto.createHash('sha256');

var code = 'bacon';

code = hash.update(code);
code = hash.digest(code);

console.log(code);

但是看起来我误解了文档作为console.log没有记录一个哈希版本的培根,而只是一些关于SlowBuffer的信息。

这样做的正确方法是什么?

3 个答案:

答案 0 :(得分:22)

base64:var hash = crypto.createHash('sha256').update(pwd).digest('base64');

十六进制:crypto.createHash('sha256').update('password').digest('hex');

答案 1 :(得分:1)

类似于上面的答案,但这显示了如何进行多次写入;例如,如果您从文件中逐行读取内容,然后将每一行作为单独的操作添加到哈希计算中。

在我的示例中,我还修剪换行符/跳过空行(可选):

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
}

我使用此代码来确保文件的生成行不会被某人手动编辑。为此,我将这些行写出来,在sha sha256:<hash>之后加上sha265-sum,然后在下一次运行时,验证这些行的哈希值是否与sha265-sum匹配。

答案 2 :(得分:0)

nodejs (8) ref

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();