Using SHA-256 with NodeJS Crypto

前端 未结 3 1553
忘了有多久
忘了有多久 2021-02-04 23:46

I\'m trying to hash a variable in NodeJS like so:

var crypto = require(\'crypto\');

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

var code = \'bacon\';

code = has         


        
3条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-05 00:08

    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: with the sha265-sum, and then, upon next run, verify the hash of those lines matches said sha265-sum.

提交回复
热议问题