Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js: crypto.pbkdf2 password to hex

I currently use following set up to register new users:

// creates a new user
app.post('/users', function(req, res) {
    // create new user
    var user = new User();
    // assign post
    user.username = req.body.username;
    user.email = req.body.email;

    crypto.randomBytes(32, function(err, buf) {
        if (err) throw err;
        user.salt = buf.toString('hex');
        crypto.pbkdf2(req.body.password, user.salt, 25000, 512, function(err, encodedPassword) {
            if (err) throw err;
            user.password = (encodedPassword.toString('hex')); // this line
            user.save(function(err, user) {
                if (!err) return res.send(err, 500);
                return res.json(user);
            });
        }.bind(this));
    });
});

Take a closer look at this line:

user.password = (encodedPassword.toString('hex'));

This should encode the password string (which looks like a binary one) into a hex string. For some reason this doesn't work.

Why not?

Byside: What encoding is recommand for salt and password storage (hex, binary, base64)?

like image 571
bodokaiser Avatar asked Jul 19 '12 09:07

bodokaiser


People also ask

How do I hash in node JS?

For example, when we create a hash we first create an instance of Hash using crypto. createHash() and then we update the hash content using the update( ) function but till now we did not get the resulting hash value, So to get the hash value we use the digest function which is offered by the Hash class.

Is crypto included in Nodejs?

js crypto module provides cryptographic functions to help you secure your Node. js app. It includes a set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify functions. crypto is built into Node.


1 Answers

It appears that if it's already a String, the toString('hex') won't work.

What I did was something like Buffer(encodedPassword, 'binary').toString('hex').

like image 149
pixelcort Avatar answered Sep 25 '22 02:09

pixelcort