Created
October 12, 2015 15:26
-
-
Save AndiDittrich/a7f2d67f91a178bd64b6 to your computer and use it in GitHub Desktop.
Simple Wrapper to access Node.js Hash functions provided by the buildin Crypto API
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
// hex output - base64 or binary also possible! | |
var Hash = require('./Hash')('hex'); | |
console.log(Hash.sha1('Hello World')); | |
// 0a4d55a8d778e5022fab701977c5d840bbc486d0 | |
console.log(Hash.sha384({ | |
title: 'Hello', | |
content: 'World!' | |
})); | |
// 1cf1e80e46390143ac12b27916b0c7bb6e3f484119b3ed69cb42d587e8aa0308ea43b29ea4af0eb53742fb7e7e0550c8 |
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'); | |
// generic string hashing | |
function hash(input, algo, type){ | |
// string input ? | |
if (typeof input !== 'string'){ | |
input = JSON.stringify(input); | |
} | |
// create hash algo | |
var sum = _crypto.createHash(algo); | |
// set content | |
sum.update(input); | |
// calculate hashsum | |
return sum.digest(type); | |
} | |
// export all function | |
module.exports = function(outputType){ | |
// default value | |
outputType = outputType || 'hex'; | |
return { | |
md5: function(input) { | |
return hash(input, 'md5', outputType); | |
}, | |
sha1: function(input) { | |
return hash(input, 'sha1', outputType); | |
}, | |
sha256: function(input) { | |
return hash(input, 'sha256', outputType); | |
}, | |
sha384: function(input) { | |
return hash(input, 'sha384', outputType); | |
}, | |
sha512: function(input) { | |
return hash(input, 'sha512', outputType); | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment