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;
}
The salt value is generated at random and can be any length; in this case the salt value is 16 bytes long. The salt value is appended to the plaintext password and then the result is hashed, which is referred to as the hashed value. Both the salt value and hashed value are stored.
Salting is simply the addition of a unique, random string of characters known only to the site to each password before it is hashed, typically this “salt” is placed in front of each password. The salt value needs to be stored by the site, which means sometimes sites use the same salt for every password.
A cryptographic salt is made up of random bits added to each password instance before its hashing. Salts create unique passwords even in the instance of two users choosing the same passwords. Salts help us mitigate hash table attacks by forcing attackers to re-compute them using the salts for each user.
Every salt should ideally have a long salt value of at least the same length as the output of the hash. If the output of the hash function used is 256 bits or 32 bytes, the length of the salt value should at least be 32 bytes.
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')
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With