authentication utils
parent
7ca553da5a
commit
7c570c4f57
@ -0,0 +1,60 @@
|
||||
/*
|
||||
* This file is part of the authRXBN single sign-on package.
|
||||
*
|
||||
* (c) Ruben Meyer <contact@rxbn.de>
|
||||
*/
|
||||
|
||||
// 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;
|
Loading…
Reference in New Issue