问题
I have to translate this Python code to NodeJS:
from passlib.hash import pbkdf2_sha256
pbkdf2_sha256.verify('12345678', '$pbkdf2-sha256$2000$8R7jHOOcs7YWImRM6V1LqQ$CIdNv8YlLlCZfeFJihZs7eQxBsauvVfV05v07Ca2Yzg')
>> True
The code above is the entire code, i.e. there is no othe parameters/settings (just run pip install passlib
before you run it to install the passlib
package).
I am looking for the correct implementation of validatePassword
function in Node that will pass this positive implementation test:
validatePassword('12345678', '$pbkdf2-sha256$2000$8R7jHOOcs7YWImRM6V1LqQ$CIdNv8YlLlCZfeFJihZs7eQxBsauvVfV05v07Ca2Yzg')
>> true
Here is the documentation of the passlib.hash.pbkdf2_sha256 with its default parameters' values.
I tried to follow the answers from here with the data from the Python code above, but that solutions didn't pass the test.
I would appreciate some help with this implementation (preferably using built-in NodeJS crypto
package).
Thank you in advance.
回答1:
This would work:
const crypto = require('crypto')
function validatePassword(secret, format) {
let parts = format.split('$')
return parts[4] == crypto.pbkdf2Sync(secret, Buffer.from(parts[3].replace(/\./g, '+') + '='.repeat(parts[3].length % 3), 'base64'),
+parts[2], 32, parts[1].split('-')[1]).toString('base64').replace(/=/g, '').replace(/\+/g, '.')
}
回答2:
You can use the crypto.pbkdf2
native node.js api
const crypto = require('crypto');
crypto.pbkdf2('secret', 'salt', 100000, 64, 'sha256', (err, derivedKey) => {
if (err) throw err;
console.log(derivedKey.toString('hex')); // '3745e48...08d59ae'
});
It is having the following api:
password <string>
salt <string>
iterations <number>
keylen <number>
digest <string>
callback <Function>
err <Error>
derivedKey <Buffer>
So you will need to play with the input variables to get the expected result as in python.
An alternative approach
I played with input variables, with not much success, and the simplest idea that I got is to make python scripts that validate the passwords and invoking it with child_process.spawn
in node.js.
来源:https://stackoverflow.com/questions/51613990/nodejs-implementation-for-pythons-pbkdf2-sha256-verify