webio-node/libs/crypto.js

31 lines
714 B
JavaScript
Raw Normal View History

2017-03-22 05:35:45 +00:00
var crypto = require('crypto');
var random = (len = 32) => {
var buf = crypto.randomBytes(len);
return buf.toString("hex");
}
var sha256 = (str) => {
return crypto.createHash("sha256").update(str).digest('base64');
}
var genPassHash = (str) => {
var hash = random(16);
var pass = sha256(str + hash);
return `$${hash}$${pass}`;
}
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: random,
sha256: sha256,
genPassHash: genPassHash,
comparePass: comparePass
}