2012-07-19 49 views
5

我目前使用以下設置註冊新用戶:的Node.js:crypto.pbkdf2密碼爲十六進制

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

乘坐這條線仔細一看:

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

這應該編碼密碼字符串(它看起來像一個二進制)到十六進制字符串。 由於某種原因,這是行不通的。

爲什麼不呢?

Byside: 對於鹽和密碼存儲(十六進制,二進制,base64)推薦使用哪種編碼?

+0

備註我發現一個線程,推薦base64超過十六進制,因爲它比較短(2.2到1.3相對於buff,二進制) – bodokaiser 2012-07-19 09:16:19

+0

我有一堆陷阱作爲該函數的輸出。由於我不知道如何處理,我明白爲什麼'toString('hex')'會失敗。祝你好運! – 2012-07-19 14:17:18

+1

注意:看起來你返回一個包含各種字符的字符串。嘗試先轉換爲字節數組(檢查stackoverflow),然後轉換爲十六進制。我討厭不理解字符串和字節之間差異的語言,而JavaScript在這個恥辱列表中肯定非常高。 – 2012-07-19 14:29:27

回答

9

看來如果它已經是一個字符串,toString('十六進制')將無法正常工作。

我所做的就像Buffer(encodedPassword, 'binary').toString('hex')