Programmers, please don’t store passwords

Mat Ryer
2 min readJul 11, 2015

--

If you ever forget your password on a website and they send you an email saying; “Here’s your password, remember: ScoldingABanana” — then they are storing your password.

I don’t like that. I don’t think websites should store passwords.

“What are you talking about — surely they HAVE to store the password, otherwise how do they know whether users have entered the correct one when logging in?”

I’m so pleased you asked that question. Here’s one way to avoid storing passwords.

Instead of storing the plain text of the password, run it through a one-way hash algorithm (with some secret sauce — called salt) and store that. Then when you need to validate a username/password combo, just run the password through the same algorithm and compare the results. If they’re the same, they must have entered the correct password — it not, they got it wrong. So we don’t need to store the password at all.

As some have pointed out, each user should get their own salt for additional security.

To see how this works, let’s see how that might look in code using the bcrypt package in the standard library in Go:

// generate password hash
hash, err := bcrypt.GenerateFromPassword(password+salt, bcrypt.DefaultCost)
// TODO: store the hash// later, when they try to log in again...
if err := bcrypt.CompareHashAndPassword(hash, password+salt); err != nil {
log.Fatalln("incorrect password")
}

A user data structure might look like this:

type User struct {
Username string
PasswordHash []byte
Salt []byte
// other fields
}

Notice that we are only storing the hash and salt, and not the password itself.

Thanks to @NuttySwiss and Matthew Holt for their comments as well as everyone on Reddit who kindly pulled my first version to pieces.

--

--

Mat Ryer

Founder at MachineBox.io — Gopher, developer, speaker, author — BitBar app https://getbitbar.com — Author of Go Programming Blueprints