hasmet hasmet - 2 years ago 219
Node.js Question

Node.js crypto.pbkdf2Sync password does not match with python script

I have a mongodb server that stores password generated by this node.js code:

encryptPassword(password, callback) {
if (!password || !this.salt) {
return null;

var defaultIterations = 10000;
var defaultKeyLength = 64;
var salt = new Buffer(this.salt, 'base64');

if (!callback) {
return crypto.pbkdf2Sync(password, salt, defaultIterations, defaultKeyLength)

return crypto.pbkdf2(password, salt, defaultIterations, defaultKeyLength, (err, key) => {
if (err) {
} else {
callback(null, key.toString('base64'));

But the authentication phase is executed by a python script that take the plain text password and should reconstruct the same password of node.js.
I'm trying to do that using both hashlib and pbkdf2 from django python modules but the results did not match. The hashlib script is:

salt = base64.b64encode(b'salt')
hashedPassword = hashlib.pbkdf2_hmac('sha1', b'password', salt, 10000, 64)
encodedPassword = base64.b64encode(res)

Do you have any ideas?

Answer Source

In your Node code, you have this:

var salt = new Buffer(this.salt, 'base64');

This assumes that this.salt is a Base64 encoded string containing the salt. It is subsequently decoded into a Buffer. So, salt is a (binary) buffer.

In your Python code, you have this:

salt = base64.b64encode(b'salt') 

This takes the binary string salt and Base64-encodes it. So, salt is a (Base64-encoded) string.

Notice the type mismatch between Node (binary buffer) and Python (Base64-encoded string)?

Instead, use this in your Python code:

salt = b'salt'

Or allow the Python code to take a Base64-encoded string as salt, and decode it:

salt = base64.b64decode('c2FsdA==')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download