Coding with Kenny

Coding with Kenny

THE BIG PICTURE: Storing User Passwords

THE BIG PICTURE: Storing User Passwords

A not-too technical exploration for beginner developers

What do you do with your users' passwords?!

We've all heard about embarrassing leaks of user information. What exactly gets revealed? Is your password exposed, NAKED, for all to see?

Thankfully, no. Your password is probably stored as a salt and a hash. So what's exposed would be that and other personal information that may be associated with your account.

I'm going to breach my own database and show you what a single users record might look like:

"_id": "60d53b94856bfb0015bdb780",
"firstName": "Bart",
"lastName": "Simpson",
"email": "",
"username": "cowabunga",
"salt": "78a1bf20ff30ef2bce920866375622555f4aae39ff56de1dcea3daf16f4d6345",
"hash": "f88f9b7a2695a9b55190d53d32c102f3becfd4c5dec3fd40202397ebfea3f50"

Cool right?! The seemingly random strings of letters and numbers in this code are the user's hashed password and salt.

This is one good way to store your users' passwords.

What is a Hash?

A hash, in this case, is just a representation of your password after it is processed by a hashing algorithm.

Now, what is a hashing algorithm? It's a set of steps that the password you entered goes through before it's comes out as a hash.

So, for example, if we pass our password 123456 through a hashing algorithm we get:

123456 =>(Hashing Algorithm) => f88f9b7a2695a9b55190d53d

When you type your password into a login page, the same hashing algorithm applied to your password when it was created is applied again. Then the hashed value is compared with whatever is saved in the database. If the values match, you're in!

What is a Salt?

A salt is some data that is added to your password before it gets processed by the hashing algorithm. The salt improves the security of your password database by neutralizing certain attack strategies.

So, another example, let's add the salt 2ju7 to our users password before we hash it

2ju7123456 =>(Hashing Algorithm) =>$2b$10$GwEyb8MEVxUW3py

And that's all there is to it! Different input and we get a different hash output.

This sounds complicated. What does it look like in practice?

Because this problem has already been solved there are awesome libraries out there that make hashing and salting easy. You can hash and salt your passwords with just a few lines of code. Let's look at an example:

import * as bcrypt from "bcrypt";

let password = "123456";

(async function outputHash() {
  let salt = await bcrypt.genSalt();
  let passwordHash = await bcrypt.hash(password, salt);

// passwordHash = $2b$10$GwEyb8MEVxUW3py99.EQoexq4cEds.ZwVWLuTgK/EaWf3Gsg40JOG


That's it! Now you know what to do with user passwords before you store them and are aware of some techniques and best practices that are needed to do it right.

Share this