【问题标题】:Using SHA-256 with NodeJS Crypto将 SHA-256 与 NodeJS 加密一起使用
【发布时间】:2015-03-14 06:13:26
【问题描述】:

我正在尝试像这样在 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 没有记录 bacon 的散列版本,而只是记录了有关 SlowBuffer 的一些信息。

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

【问题讨论】:

标签: node.js node-crypto


【解决方案1】:

base64:

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

十六进制:

crypto.createHash('sha256').update(pwd).digest('hex');

【讨论】:

  • 不要使用 sha256 散列密码?查找 bcrypt 或类似的东西。
【解决方案2】:

你可以使用,像这样,在这里创建一个重置令牌(resetToken),这个令牌用于创建一个十六进制版本。在数据库中,你可以存储十六进制版本。

// Generate token
 const resetToken = crypto.randomBytes(20).toString('hex');
// Hash token and set to resetPasswordToken field
this.resetPasswordToken = crypto
    .createHash('sha256')
    .update(resetToken)
    .digest('hex');

console.log(resetToken )

【讨论】:

    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

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

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

      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
      }
      

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-05-10
        • 2017-03-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-24
        • 2017-02-13
        相关资源
        最近更新 更多