Skip to content

Instantly share code, notes, and snippets.

@GuillermoPena
Created February 26, 2014 16:30
Show Gist options
  • Star 33 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save GuillermoPena/9233069 to your computer and use it in GitHub Desktop.
Save GuillermoPena/9233069 to your computer and use it in GitHub Desktop.
NodeJS - CRYPTO : How to calculate a hash from file or string
var crypto = require('crypto')
, fs = require('fs')
// Algorithm depends on availability of OpenSSL on platform
// Another algorithms: 'sha1', 'md5', 'sha256', 'sha512' ...
var algorithm = 'sha1'
, shasum = crypto.createHash(algorithm)
// Updating shasum with file content
var filename = __dirname + "/anything.txt"
, s = fs.ReadStream(filename)
s.on('data', function(data) {
shasum.update(data)
})
// making digest
s.on('end', function() {
var hash = shasum.digest('hex')
console.log(hash + ' ' + filename)
})
// Calculating hash from string
var textToHash = "Hello, I want a hash from it"
, shasum2 = crypto.createHash(algorithm)
shasum2.update(textToHash)
var hash2 = shasum2.digest('hex')
console.log(hash2 + ' ' + textToHash)
@ziozec-zz
Copy link

What about a sync version of the has? Thanks

@funnyzak
Copy link

funnyzak commented Feb 28, 2018

function fileHash(filename, algorithm = 'md5') {
  return new Promise((resolve, reject) => {
    // Algorithm depends on availability of OpenSSL on platform
    // Another algorithms: 'sha1', 'md5', 'sha256', 'sha512' ...
    let shasum = crypto.createHash(algorithm);
    try {
      let s = fs.ReadStream(filename)
      s.on('data', function (data) {
        shasum.update(data)
      })
      // making digest
      s.on('end', function () {
        const hash = shasum.digest('hex')
        return resolve(hash);
      })
    } catch (error) {
      return reject('calc fail');
    }
  });
}

@iShafayet
Copy link

@funnyzak Promises are not synchronous.

@xardbaiz-zz
Copy link

xardbaiz-zz commented Mar 15, 2018

@iShafayet you can always use async/await

turn function to async
async function fileHash(filename, algorithm = 'md5')

then

var hash = await fileHash('file'); console.log("it's sync!!"+hash);

@lhoff
Copy link

lhoff commented Apr 26, 2018

Promises are then-able:

fileHash('file').then((hash) => { 
  console.log(hash);
});

@styfle
Copy link

styfle commented Jul 2, 2018

The Node.js documentation has a pretty good example showing how to make a sha256 CLI.

// sha-cli.js
const filename = process.argv[2];
const crypto = require('crypto');
const fs = require('fs');
const hash = crypto.createHash('sha256');
const input = fs.createReadStream(filename);
input.on('readable', () => {
  const data = input.read();
  if (data)
    hash.update(data);
  else {
    console.log(`${hash.digest('hex')} ${filename}`);
  }
});

Example usage if you saved that code in sha-cli.js file would be:

node sha-cli.js example-input-file.zip

@moeiscool
Copy link

I compiled the dope comments into a fork of this gist. Thanks guys!! https://gist.github.com/moeiscool/fa7401e44965243f1dd42cfe5abfe015

@enijar
Copy link

enijar commented Dec 11, 2019

Those looking for a more compact function can use the following.

const createHashFromFile = filePath => new Promise(resolve => {
  const hash = crypto.createHash('sha1');
  fs.createReadStream(filePath).on('data', data => hash.update(data)).on('end', () => resolve(hash.digest('hex')));
});

Call it using the following.

(async () => {
  console.log(await createHashFromFile(__filename));
})();

@romellem
Copy link

For a synchronous method of this, use readFileSync rather than Readable Streams.

const crypto = require('crypto');
const fs = require('fs');

let file_buffer = fs.readFileSync('path/to/your/file.txt');
let sum = crypto.createHash('sha256');
sum.update(file_buffer);
const hex = sum.digest('hex');

console.log(hex);

@shraddha27
Copy link

Thankyou so much romellem. May God Bless Always

@misostack
Copy link

Note

@razorcell
Copy link

Many thanks.

@lauBit
Copy link

lauBit commented May 31, 2021

what are the libraries to install for SHA256 to work?

@peeyush-es
Copy link

thanks @romellem

@AttilaTheHun
Copy link

awesome, thank you @romellem !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment