Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
166
rated 0 times [  172] [ 6]  / answers: 1 / hits: 48264  / 12 Years ago, tue, july 17, 2012, 12:00:00

I want to create a salt-hash using node.js crypto lib without having to parse any hardcoded data.



What do I mean with hardcoded?



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


Isn't there any other way how I can create a random string without using raw javascript, random functions or hardcoding something?



Regards



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;
}

More From » node.js

 Answers
46

A quick look at the documentation turns up the crypto.randomBytes function.



var buf = crypto.randomBytes(16);


This returns a buffer containing raw bytes. If you want a string, you can use toString('base64') or toString('hex').


[#84215] Sunday, July 15, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bradley

Total Points: 555
Total Questions: 102
Total Answers: 99

Location: Tajikistan
Member since Fri, Nov 27, 2020
4 Years ago
;