lora-project/server-api/libs/crypto.js

48 lines
873 B
JavaScript
Raw Normal View History

2017-06-01 10:09:25 +00:00
var crypto = require('crypto');
2017-06-01 14:37:51 +00:00
/**
*
* @param {number} len
*/
2017-06-01 10:09:25 +00:00
var random = (len = 32) => {
var buf = crypto.randomBytes(len);
return buf.toString("hex");
}
2017-06-01 14:37:51 +00:00
/**
*
* @param {string} str
*/
2017-06-01 10:09:25 +00:00
var sha256 = (str) => {
return crypto.createHash("sha256").update(str).digest('base64');
}
2017-06-01 14:37:51 +00:00
/**
*
* @param {string} str
*/
2017-06-01 10:09:25 +00:00
var genPassHash = (str) => {
var hash = random(16);
var pass = sha256(str + hash);
return `$${hash}$${pass}`;
}
2017-06-01 14:37:51 +00:00
/**
*
* @param {string} plain
* @param {string} hash
*/
2017-06-01 10:09:25 +00:00
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
}