Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moeiscool/fa7401e44965243f1dd42cfe5abfe015 to your computer and use it in GitHub Desktop.
Save moeiscool/fa7401e44965243f1dd42cfe5abfe015 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)
//by funnyzak from the original repo's comments
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');
}
});
}
// sha-cli.js by styfle from the original repo's comments
// Hash file from CLI with node script.
// example use : node sha-cli.js example-input-file.zip
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}`);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment