sql >> Base de Datos >  >> NoSQL >> MongoDB

¿Cómo almacenar crypto pbkdf2 en mongoDB?

Almacenar el hash como una cadena hexadecimal en la base de datos funciona bien para mí (almacenarlos 'sin procesar' en una String o un Buffer propiedad no):

var crypto      = require('crypto');
var mongoose    = require('mongoose');
var client      = mongoose.connect('mongodb://localhost/test');
var UserSchema  = new mongoose.Schema({
  salt  : String,
  hash  : String
});

var User = mongoose.model('User', UserSchema);

hash('secret', function(err, salt, key) {
  new User({ salt : salt, hash : key.toString('hex') }).save(function(err, doc) {
    User.findById(doc._id, function(err, doc) {
      hash('secret', doc.salt, function(err, key) {
        console.log('eq', doc.hash === key.toString('hex'));
      });
    });
  });
});

(por cierto, ambos crypto.pbkdf2 y crypto.randomBytes tienen contrapartes síncronas)