48 lines
873 B
JavaScript
48 lines
873 B
JavaScript
var crypto = require('crypto');
|
|
|
|
/**
|
|
*
|
|
* @param {number} len
|
|
*/
|
|
var random = (len = 32) => {
|
|
var buf = crypto.randomBytes(len);
|
|
return buf.toString("hex");
|
|
}
|
|
|
|
/**
|
|
*
|
|
* @param {string} str
|
|
*/
|
|
var sha256 = (str) => {
|
|
return crypto.createHash("sha256").update(str).digest('base64');
|
|
}
|
|
|
|
/**
|
|
*
|
|
* @param {string} str
|
|
*/
|
|
var genPassHash = (str) => {
|
|
var hash = random(16);
|
|
var pass = sha256(str + hash);
|
|
return `$${hash}$${pass}`;
|
|
}
|
|
|
|
/**
|
|
*
|
|
* @param {string} plain
|
|
* @param {string} hash
|
|
*/
|
|
var comparePass = (plain, hash) => {
|
|
var match = hash.match(/^\$(.+?)\$(.+)$/);
|
|
if (match == null || match.length < 3 || !match[1] || !match[2]) return false;
|
|
var pass = sha256(plain + match[1]);
|
|
if (pass == match[2]) return true;
|
|
return false;
|
|
}
|
|
|
|
module.exports = {
|
|
random,
|
|
sha256,
|
|
genPassHash,
|
|
comparePass
|
|
} |