почему все сравнения brcypt или crypto-хэшей всегда возвращают false даже для правильного пароля - PullRequest
0 голосов
/ 02 мая 2019

Мне удалось использовать cryptojs и bcrypt для хеширования / шифрования всех моих паролей, но мне не удалось сравнивать хэши (хешированный пароль в базе данных с хешированным входным паролем) всегда возвращая ложь поэтому я больше копался, чтобы узнать содержимое хешей, и вот результаты.

const crypto = require('crypto')
function setUserPassword(inputPassword){
    const salt = crypto.randomBytes(16).toString('hex')
  let hashedPassword = crypto.pbkdf2Sync(inputPassword, salt, 1000, 16,'sha512').toString('hex')
   return{ //we shall store them in the database later
     salt: salt,
     hashedPassword: hashedPassword
   }
}
database ====>ac0f74b30c94fedbbd591889c4705607  //works perefectly using the above function

challenge comes when validating the user password.. using this function..
   function validateUserPassword(enteredPassword, dbSalt, dbPassword){

// then checks if this generated hash is equal to user's hash in the database or not 
   let hashInput = crypto.pbkdf2Sync(enteredPassword, dbSalt, 1000,16, 'sha512') //the same as above

   //u must compare the hashed password in the db with hashedInput password
   return hashInput === dbPassword //IF it returns true then they match
}
so i checked the  hashInput and discovered that it was a buffer instead of the string... 
hey hashed input password  <Buffer ac 0f 74 b3 0c 94 fe db bd 59 18 89 c4 70 56 07>

//may nodejs version... v6.11.4 and alo tried using v10.15.0 but all in  the vain.

1 Ответ

0 голосов
/ 02 мая 2019

В setUserPassword() вы создаете строку в шестнадцатеричном формате из буфера, возвращаемого хеш-функцией, но вы забыли сделать то же самое в validateUserPassword(). Это исправит это:

let hashInput = crypto.pbkdf2Sync(enteredPassword, dbSalt, 1000,16, 'sha512').toString('hex')
...