Password isn't getting hashed by brcypt module - node.js

I am hashing password using nodejs "bcrypt" module. this is my hashing function...
and here i am calling my function
But in databases password is not saving. In databases field is empty every time when i register. How can i fix it?
Here is database entry record

You have nothing saved inside your database because you choose to use the asynchronous bcrypt hash function.
It should work if you use the synchronous one. ( replace your bcrypt hash by this one)
let hash = bcrypt.hashSync('password', 10);
return hash;

Related

how to verify plain text key vs hashed API key

A user can generate an API key by pressing a button, and I save the API key in the database. However, I don't save it as plain text, but rather hash it. I thought this was wise until I started trying to verify the API key.
I am hashing like this:
const saltRounds = 10;
const key = crypto.randomUUID();
const hashedToken = await bcrypt.hash(key, saltRounds);
The problem now is that in the other application, the user doesn't send any user details like email address for example. So, if they had I could have done a findOne({email: email}) or if there was a user ID I could have done findById etc. but now only the API key is sent.
So, I am receiving the plain text version of the API key and need to somehow compare it.
I would have done the below but I don't actually have user.apiKey.
const validKey = await bcrypt.compare(key, user.apiKey);
So, if all I have is the plain text API key, how can I find it and compare it in the database?
I came up with a solution but not sure if it is any good. Basically what I ended up doing is creating a prefix for the api key and concatenating it with the actual API key.
const concatKey = keyPrefix + "." + token;
So, I save keyPrefix in the database and use that as the unique ID. I also save a hash of concatKey.
Then when I send requests to the API, I split the api key and get the prefix before the . and look that up in the database ie: the unique identifier. I then compare the hashes and if all okay the request can proceed.
It's not pretty, but it works.

Cant use original password, after hash (pgcrypto)

I have succeded in hashing my password for my admin user, the problem is now that i can no longer use the original password to log in (no errors, exept the correct response for invalid passwords). I am able to to select the user table and just copy in the hashed password from PGadmin (using PostgreSQL). Im not really sure where to go from here.
1. I think i have to get my login form to recognize the hashed password, and somehow match it up with the original.
2. figure out how to add salt and pepper to the hash
I am not looking for the exact solution, but maybe some hints to get further :)
Code
function createAdmin(){
var usertypeid = null;
const type = "adm";
pool.query(`INSERT INTO usertype(type) VALUES ($1) RETURNING userTypeId;`, [type], function (error, results) {
if (error){
throw error;
} else{
usertypeid = results.rows[0].usertypeid;
console.log(usertypeid);
insertAdmin();
}
});
function insertAdmin(){
pool.query(`
INSERT INTO users(
usertypeid, userName, email, password)
VALUES($1, 'admin', 'admin#admin.com', CRYPT('admin', GEN_SALT('md5')));`, [usertypeid]);
}
}
As mentioned in the comments, don't use MD5 anymore as it's deprecated a long time ago.
The other thing is that hashing is different from encrypting. You can't decrypt a hash like you do with a cipher.
What should happen is that you run the plaintext through the hashing algorithm and then see if it matches the original hash computed at the beginning.
For Node.js there are good libraries out there like bcrypt which can be used to simplify the process and perhaps make it more secure.
If you insist to perform your own validation procedure, then it should be like the following:
Get the user's password from the login form
Run it through the hashing algo of your choice (no MD5 please)
Query the database for the hashed password
Compare if the hashed password from the login form is the same as the one in the DB
As the docs say, you want something like this (renaming table and columns to match your example):
SELECT (password = crypt('entered password', password)) AS pswmatch FROM users where username='admin';
The value stored in users.password from your insertion is a combination of the algorithm, the salt, and result of hashing the actual password with that algorithm and salt. Now you pass users.password into crypt again, so that it can extract from it the algorithm and the salt. It then uses that algorithm and salt to recompute the hash of the alleged password. If the re-computed value matches the stored value, then the alleged password is correct.

How does bcrypt know which hashed method has been used

I have a key which is salted and hashed using SHA-256. if I use bcrypt for compare this, Dose bcrypt know which hashing method has been using for hash the key. Or I need to define the method in somewhere.
bcrypt.compare("string","base256-hashed-and-salted-key", function(err, res) {
// res == true
});
The first parameter is the string you're wanting to check (e.g. password from a login form). The second parameter is the hash value you got as a result of bcrypt.hash() that you retrieve from a database or some other data store.
bcrypt does not care if the string you hash is pre-hashed with SHA-256 or if it's just the plain text password itself. bcrypt hashes any kind of data.

Yii2 - how to properly use generatePasswordHash()?

I'm trying to generate a random password for a user in a Yii2 application.
I have the following code:
$rand_password = Yii::$app->security->generateRandomString(8);
$user->password = Yii::$app->security->generatePasswordHash($rand_password);
After that I save the $user model and the hashed string is also saved in the database. However, I cannot log in with the $rand_password string after that as I'm getting Invalid Password error message.
The generatePasswordHash description says that the hash is generated from the provided password and a random salt string. Indeed, I called the function with the same password string several times in a row and I got different result every time. So my question is, if that salt string is random and different every time, how can I use this function at all to verify passwords? When I try to login I call the same function with the password string provided by the user but this time the salt will be different so I'm unable to produce the same hash as before? What am I missing here?
Well, after hours of debugging and looking for resources and explanation, it turns out the the user module I'm using: https://github.com/amnah/yii2-user is actually automatically hashing the passwords before saving them in the database. In other words, as soon as you call:
$user->password = SOMETHING;
that SOMETHING is automatically going through the generatePasswordHash() function upon save. My problem was that I was dropping it in there in my code as well so basically the password got hashed twice.

simple mail/password registration with crypto.js

I'm trying to save passwords in my database, and I want to hash them with either MD5 or SHA2.
I googled it and found a lot of very different topics with long lines of code all the time, I don't know why.
Isn't it possible to store a password with one line of code with crypto.js ?
e.g.
var crypto = require('crypto-js')
collection.insert(user: "my user", password: crypto.sha2("my-password")
So later, I can do the simplest auth ever and process the result of this db request:
db.findOne({use:"my user", password: crypto.sha2("my-password") etc...
You shouldn't use general-purpose hash algorithms such as SHA-2 for storing passwords. See: http://codahale.com/how-to-safely-store-a-password/

Resources