5

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)?

bodokaiser
  • 15,122
  • 22
  • 97
  • 140
  • For the byside note I found a thread which recommands base64 over hex because it is shorter (2.2 to 1.3 in relation to buff, binary) – bodokaiser Jul 19 '12 at 09:16
  • I got a bunch of trap as output from that function. As I don't have a clue how to handle that either, I understand why `toString('hex')` would fail. Good luck! – Maarten Bodewes Jul 19 '12 at 14:17
  • 1
    Note: it seems that you get returned a string containing all kinds of characters. Try to convert to byte array first (check stackoverflow) and then convert to hex. I hate languages that don't understand the difference between strings and bytes, and JavaScript is certainly very very high up that list of shame. – Maarten Bodewes Jul 19 '12 at 14:29
  • @owlstead could you give me a code snippet how I can convert a buffer, byte to string? I also could mark this as answer – bodokaiser Jul 19 '12 at 15:30
  • I wish I could find a good implementation but I haven't found anything in the default javascript functions. Maybe try [this](http://stackoverflow.com/questions/6965107/converting-between-strings-and-arraybuffers), although I don't know if this applies to the Node.js runtime. – Maarten Bodewes Jul 19 '12 at 19:12

1 Answers1

9

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').

pixelcort
  • 249
  • 3
  • 15