From 7c570c4f574d2a7720841d10dfa1beaa810725cf Mon Sep 17 00:00:00 2001 From: Ruben Meyer <46384706+rxbnDE@users.noreply.github.com> Date: Wed, 19 Jun 2019 00:45:48 +0200 Subject: [PATCH] authentication utils --- bin/auth/module.js | 60 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 bin/auth/module.js diff --git a/bin/auth/module.js b/bin/auth/module.js new file mode 100644 index 0000000..795d551 --- /dev/null +++ b/bin/auth/module.js @@ -0,0 +1,60 @@ +/* + * This file is part of the authRXBN single sign-on package. + * + * (c) Ruben Meyer + */ + +// init +var methods = {}; +var crypto = require('crypto'); + +/** + * Generating Hash + * @author Ruben Meyer + * @param {String} key "user password" + * @param {String} salt (OPTIONAL) + * @return {String} + */ +methods.generateHash = (key, salt) => { + if(typeof salt !== 'string') { + let length = 16; + salt = crypto.randomBytes(Math.ceil(length/2)).toString('hex').slice(0, length); + } else { + salt = salt; + } + + let hash = crypto.createHmac('sha512', salt); + hash.update(key); + hash = hash.digest('hex'); + + return hash+'|'+salt; +}; + +/** + * validate hashed password + * @author Ruben Meyer + * @param {String} hash "hashed password" + * @param {String} key "plaintext password" + * @return {Boolean} + */ +methods.validateHash = (hash, key) => { + if(typeof hash !== 'string' || typeof key !== 'string') return false; + + let salt = hash.split('|')[1]; + let generated = methods.generateHash(key, salt); + + if( + hash.split('|')[0].length === generated.split('|')[0].length + && + crypto.timingSafeEqual( + Buffer.from(generated.split('|')[0], 'hex'), + Buffer.from(hash.split('|')[0], 'hex') + ) + ) { + return true; + } + + return false; +}; + +module.exports = methods;