Search code examples
javascriptdjango-authenticationsha256pbkdf2

Django pbkdf2_sha256 JS implementation


I have a database from django and I want to work with it from Node.js. I have a task: authenticate users. Known from database: algorithm pbkdf2_sha256, salt, 10000 iterations and base64-encoded hash. What steps I must to do in JS to encode some password to given base64-hash?

UPD: found the solution in here: python (django) hashlib vs Nodejs crypto but Django-generated hash and JS-generated hash not match...
Django generate next:

pbkdf2_sha256$10000$NmzpPCQiTe2R$U8ipSsOy3Xz7FwWDHdH/dTei8Xh4Q7NGtdzrCacSfvo=

JS:

pbkdf2_sha256$10000$NmzpPCQiTe2R$w4jCgWjDilrDmcOBd8K+I8OdwpkKwoVQZMKWH3FvYcKoAMKcwqlewobDocOEGMKZfQ==

Password: Simple123


Solution

  • By using pbkdf2-sha256 (from your own link) I'm able to generate a hash that is identical to the one you have from Django.

    var pbkdf2 = require('pbkdf2-sha256');
    var validatePassword = function (key, string) {
        var parts = string.split('$');
        var iterations = parts[1];
        var salt = parts[2];
        return pbkdf2(key, new Buffer(salt), iterations, 32).toString('base64') === parts[3];
    };
    var djangoPass = 'pbkdf2_sha256$10000$NmzpPCQiTe2R$U8ipSsOy3Xz7FwWDHdH/dTei8Xh4Q7NGtdzrCacSfvo=';
    console.log(validatePassword('Simple123', djangoPass)); // Logs: true
    

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