Created
February 26, 2014 16:30
-
-
Save GuillermoPena/9233069 to your computer and use it in GitHub Desktop.
NodeJS - CRYPTO : How to calculate a hash from file or string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Many thanks.
what are the libraries to install for SHA256 to work?
thanks @romellem
awesome, thank you @romellem !
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);
... until the file size exceeds 2GB, then this doesn't work anymore
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note