2019-06-18 22:45:48 +00:00
|
|
|
/*
|
|
|
|
* This file is part of the authRXBN single sign-on package.
|
|
|
|
*
|
|
|
|
* (c) Ruben Meyer <contact@rxbn.de>
|
|
|
|
*/
|
|
|
|
|
|
|
|
// init
|
|
|
|
var methods = {};
|
|
|
|
var crypto = require('crypto');
|
|
|
|
|
2020-08-14 11:23:05 +00:00
|
|
|
var cfg = require(global['__dirname']+'/bin/config');
|
|
|
|
delimiter = cfg.app.passhashDelimiter;
|
|
|
|
|
2019-06-18 22:45:48 +00:00
|
|
|
/**
|
2020-08-14 11:23:05 +00:00
|
|
|
* returns a hash|salt combination
|
2019-06-18 22:45:48 +00:00
|
|
|
* @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');
|
|
|
|
|
2020-08-14 11:23:05 +00:00
|
|
|
return hash+delimiter+salt;
|
2019-06-18 22:45:48 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
2020-08-14 11:23:05 +00:00
|
|
|
* validates a hashed input
|
2019-06-18 22:45:48 +00:00
|
|
|
* @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;
|
|
|
|
|
2020-08-14 11:23:05 +00:00
|
|
|
let salt = hash.split(delimiter)[1];
|
2019-06-18 22:45:48 +00:00
|
|
|
let generated = methods.generateHash(key, salt);
|
|
|
|
|
|
|
|
if(
|
2020-08-14 11:23:05 +00:00
|
|
|
hash.split(delimiter)[0].length === generated.split(delimiter)[0].length
|
2019-06-18 22:45:48 +00:00
|
|
|
&&
|
|
|
|
crypto.timingSafeEqual(
|
2020-08-14 11:23:05 +00:00
|
|
|
Buffer.from(generated.split(delimiter)[0], 'hex'),
|
|
|
|
Buffer.from(hash.split(delimiter)[0], 'hex')
|
2019-06-18 22:45:48 +00:00
|
|
|
)
|
|
|
|
) {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
return false;
|
|
|
|
};
|
|
|
|
|
|
|
|
module.exports = methods;
|