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

49 lines
824 B
JavaScript
Raw Normal View History

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