Search code examples
pythondjangonode.jshashlibpassport.js

python (django) hashlib vs Nodejs crypto


I'm porting over a Django site to Node.js and I am trying to re implement the Django set password method in Node. This is the Django code

from django.utils.crypto import (
    pbkdf2, get_random_string)

import hashlib

password = 'text1'
algorithm = "pbkdf2_sha256"
iterations = 10000
salt = 'p9Tkr6uqxKtf'
digest = hashlib.sha256
hash = pbkdf2(password, salt, iterations, digest=self.digest)
hash = hash.encode('base64').strip()
print "%s$%d$%s$%s" % (self.algorithm, iterations, salt, hash)

and here's the Node.js code I have so far:

var password = 'text1';
var hashed = crypto.createHash('sha256').update(password, 'utf8').digest();
var salt = 'p9Tkr6uqxKtf';
var algorithm = "pbkdf2_sha256";
var iterations = 10000;
crypto.pbkdf2(hashed, salt, iterations, 32, function(err, encodedPassword) {
    var newPass = new Buffer(encodedPassword).toString('base64');
    console.log(encodedPassword);

    // console.log(Buffer(encodedPassword, 'binary').toString('hex'));
    var finalPass = algorithm +'$'+ iterations +'$'+  salt +'$'+  newPass;
    console.log(finalPass);
});

My solution in Node doesn't output the same results as the Python / Django code. At this point I'm pretty much over my head and any help would be very much appreciated. Thanks in advance.


Solution

  • Here is a better solution using pbkdf2-sha256:

    var pbkdf2 = require('pbkdf2-sha256');
    var password = 'text1';
    var salt = 'p9Tkr6uqxKtf';
    var algorithm = "pbkdf2_sha256";
    var iterations = 10000;
    var hashed = pbkdf2(password, new Buffer(salt), iterations, 32).toString('base64');
    var finalPass = algorithm +'$'+ iterations +'$'+  salt +'$'+  hashed;
    

    The above code should be sufficient to validate passwords stored in Django using Node.