Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 446
imns Avatar asked Mar 13 '13 19:03

imns


Video Answer


2 Answers

So my solution to this was to create a python script that takes the salt and users password and returns the hashed password. I call this script from node and parse the results. I check if the hashed password starts with: pbkdf2_sha256, then I validate it against what my python script returned, if it validates use my new systems hashing function to reset the password.

like image 41
imns Avatar answered Oct 15 '22 11:10

imns


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.

like image 78
paldepind Avatar answered Oct 15 '22 11:10

paldepind