webio-node/libs/crypto.js
2017-03-22 13:35:45 +08:00

31 lines
714 B
JavaScript

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
}