如何用密码创build随机encryption哈希

我想用node.jsencryption库创build一个salt-hash,而不必parsing任何硬编码的数据。

硬编码是什么意思?

var salt, hardcodedString = "8397dhdjhjh"; crypto.createHmac('sha512', hardcodedString).update(salt).digest("base64"); 

没有任何其他方式如何创build一个随机string,而不使用原始的JavaScript,随机函数或硬编码的东西?

问候

UPDATE

 var Crypto = require('crypto') , mongoose = require('mongoose'); module.exports = mongoose.model('User', new mongoose.Schema({ username: { type: String , required: true , index: { unique: true, sparse: true } , set: toLower }, email: { type: String , required: true , index: { unique: true, sparse: true } , set: toLower }, salt: { type: String , set: generateSalt }, password: { type: String , set: encodePassword } }),'Users'); function toLower(string) { return string.toLowerCase(); } function generateSalt() { //return Math.round((new Date().valueOf() * Math.random())) + ''; Crypto.randomBytes('256', function(err, buf) { if (err) throw err; return buf; }); // return Crypto.randomBytes('256'); // fails to } function encodePassword(password) { return password; // TODO: setter has no access to this.salt //return Crypto.createHmac('sha512', salt).update(password).digest("base64"); } function authenticate(plainPassword) { return encodePassword(plainPassword) === this.password; } 

快速浏览一下文档就会看到crypto.randomBytes函数。

 var buf = crypto.randomBytes(16); 

这将返回包含原始字节的缓冲区。 如果你想要一个string,你可以使用toString('base64')toString('hex')