Dev.to Security 🔐 Cybersecurity 👁 0 📖 10 min read

Password Hashing and Secrets

A Security Starter Pack There's a certain kind of news headline that makes backend developers wince: "Company X breached; millions of passwords exposed." The wince has a second layer, because the follow-up detail decid

A Security Starter Pack

There's a certain kind of news headline that makes backend developers wince: "Company X breached; millions of passwords exposed." The wince has a second layer, because the follow-up detail decides everything. Were the passwords stored in plain text, or properly hashed? One of those is a bad day. The other is a catastrophe with a press release.

This article is a starter pack for two things every backend must get right: storing passwords and handling secrets (database credentials, API keys, signing keys). Neither requires genius. Both require discipline, and a refusal to take shortcuts that feel harmless at the time.

Rule zero: never store the password

When a user signs up with the password sunshine123, your database should never contain the string sunshine123. Not encrypted, not Base64-encoded, not "obfuscated," and certainly not in a column cheerfully named password.

Why? Because breaches happen. A SQL injection, a stolen backup, a laid-off contractor, a misconfigured storage bucket. If the database is exposed and passwords are readable, every user is compromised, including on other websites, because people reuse passwords the way they reuse favorite jackets.

The goal is: even if the database leaks completely, the attacker should not be able to log in as anyone, or recover what anyone typed.

Encryption vs hashing (they are not the same thing)

Encryption is two-way. You scramble data with a key, and anyone with the key can unscramble it. Great for secrets you need to read back later, like an API token. Terrible for passwords, because the server must hold the key, and if an attacker steals the database, they often steal the key too.

Hashing is one-way. You feed in data, get a fixed-length fingerprint out, and there is no "decrypt." To check a password at login, you hash what the user typed and compare the result to the stored hash. You never need the original again.

Picture a meat grinder. You can turn steak into mince, but you can't turn mince back into steak. If someone steals your mince, they can't reconstruct your dinner. They can only try grinding lots of other steaks and see if any match, and that's the attack we need to survive.

Why plain SHA-256 isn't good enough

You might think: "Hashing, okay, SHA-256, done." Not quite. General-purpose hashes like SHA-256 and MD5 are designed to be fast. That's wonderful for checking file integrity and terrible for passwords, because an attacker with a stolen hash list can try billions of guesses per second on modern hardware.

Worse, people choose predictable passwords. Attackers keep giant lists of common ones, and also rainbow tables: precomputed hash-to-password lookups. Ever seen a database where thousands of users share the same hash? Those users all share the same password, and cracking one cracks them all.

Password hashing needs three properties that ordinary hashes lack:

  1. Salting: a unique random value mixed into each password before hashing, so identical passwords produce different hashes and precomputed tables become useless.
  2. Slowness: deliberately expensive computation, so each guess costs the attacker real time. A delay of 100 milliseconds is invisible to a human logging in, and devastating to someone trying a billion guesses.
  3. Tunability: a cost setting you can raise over the years as hardware improves.

Purpose-built algorithms provide all three: bcrypt, scrypt, and Argon2.

bcrypt: the reliable workhorse

bcrypt has protected passwords for decades, and Go's extended library supports it directly.

import "golang.org/x/crypto/bcrypt"

func HashPassword(plain string) (string, error) {
    hash, err := bcrypt.GenerateFromPassword([]byte(plain), bcrypt.DefaultCost)
    if err != nil {
        return "", fmt.Errorf("hashing password: %w", err)
    }
    return string(hash), nil
}

func CheckPassword(hash, plain string) bool {
    return bcrypt.CompareHashAndPassword([]byte(hash), []byte(plain)) == nil
}

Some details worth knowing:

  • The salt is automatic. bcrypt generates a random salt and embeds it in the output string, which looks like $2a$12$N9qo8uLOickgx2ZMRZoMye.... That string carries the algorithm version, the cost, the salt, and the hash. Store the whole thing in one column. Nothing else is needed.
  • The cost parameter controls how slow it is. DefaultCost is 10. Many teams pick 12 or so today. Choose the highest value that keeps login responsive on your real servers (aim for roughly 100 to 300 ms), and revisit it every couple of years.
  • There's a 72-byte limit. bcrypt only considers the first 72 bytes of the input, and recent versions of the Go library return an error for longer passwords rather than silently truncating. If you want to support very long passphrases, pre-hash with SHA-256 and encode before bcrypt, or choose Argon2.
  • CompareHashAndPassword is constant-time, meaning it doesn't leak information through how long it takes. Don't write your own comparison with ==.

Argon2id: the modern recommendation

Argon2 won an international password hashing competition and is generally recommended for new systems. Its special trick is being memory-hard: each hash demands a chunk of RAM, which makes attacks with specialized hardware (GPUs, custom chips) far more expensive.

The variant to use is Argon2id. In Go it lives in golang.org/x/crypto/argon2. It's a lower-level API, so you handle the salt and encoding yourself:

func HashArgon2(plain string) (string, error) {
    salt := make([]byte, 16)
    if _, err := rand.Read(salt); err != nil {
        return "", err
    }

    // time=1, memory=64MB, threads=4, key length=32
    key := argon2.IDKey([]byte(plain), salt, 1, 64*1024, 4, 32)

    return fmt.Sprintf("%s$%s",
        base64.RawStdEncoding.EncodeToString(salt),
        base64.RawStdEncoding.EncodeToString(key)), nil
}

If hand-assembling hash strings makes you nervous (reasonably), use a well-reviewed wrapper library that handles encoding and verification, or simply stay with bcrypt. A well-configured bcrypt is still far better than a poorly assembled Argon2. The choice of algorithm matters less than not rolling your own scheme and actually using a slow, salted one.

Using it in the service layer

Remember: hashing is a business rule, so it belongs in the service, not the handler. A clean way to keep it testable is to hide hashing behind a small interface:

type PasswordHasher interface {
    Hash(plain string) (string, error)
    Verify(hash, plain string) bool
}

Your AuthService takes a PasswordHasher. In production it's bcrypt. In tests, it's a cheap fake, which matters because real bcrypt at cost 12 makes a test suite feel like it's wading through honey.

Login without giving hints

Here's a subtle one. Consider this login logic:

user, err := s.users.FindByEmail(ctx, email)
if err != nil {
    return ErrInvalidCredentials
}
if !s.hasher.Verify(user.PasswordHash, password) {
    return ErrInvalidCredentials
}

The error message is the same in both cases. Good: never say "no such user" versus "wrong password," because that lets attackers discover which emails are registered. But look closer. When the user doesn't exist, the function returns instantly. When the user exists, it spends 200 ms hashing. An attacker with a stopwatch can still tell the two cases apart. This is a timing attack.

The fix is to burn the same time either way by verifying against a dummy hash when the user isn't found:

// computed once at startup: hash of a random string
var dummyHash = mustHash("not-a-real-password-just-a-placeholder")

user, err := s.users.FindByEmail(ctx, email)
if err != nil {
    s.hasher.Verify(dummyHash, password) // spend the same time
    return ErrInvalidCredentials
}

It looks silly, like a bank teller pretending to check a vault for an account that doesn't exist. But it keeps the response time uniform.

Password policy: what actually helps

Forget the old rules about forcing one capital, one symbol, and one number. They produce passwords like Password1!, which meets every rule and falls in seconds. Better guidance:

  • Require a minimum length (8 is the floor, 12 is friendlier).
  • Allow long passphrases and any characters, including spaces and emoji.
  • Check against lists of common or breached passwords, which is the single most helpful rule.
  • Don't force periodic changes without a reason, since that breeds Summer2024!, then Autumn2024!.
  • Rate-limit login attempts so guessing is slow even before hashing enters the picture.

And offer multi-factor authentication where the stakes justify it.

Secrets: the things that must not be in your repository

Now the other half. Your app has secrets: the database password, the JWT signing key, a payment provider's API key, an email service token. The cardinal sin is putting them in your source code.

// Please, no.
const jwtSecret = "my-super-secret-key"
db := connect("postgres://admin:hunter2@prod-db:5432/app")

Git remembers everything. Commit a secret once and it lives in history forever, even if you delete it in the next commit. Bots scan public repositories for leaked keys within minutes. A credential that touched a public repo, even briefly, should be treated as compromised and rotated (replaced with a new one).

Environment variables: the baseline

Configuration that changes between environments, and secrets in particular, should come from the environment:

type Config struct {
    DatabaseURL string
    JWTSecret   string
    Port        string
}

func Load() (*Config, error) {
    cfg := &Config{
        DatabaseURL: os.Getenv("DATABASE_URL"),
        JWTSecret:   os.Getenv("JWT_SECRET"),
        Port:        getenvDefault("PORT", "8080"),
    }

    if cfg.DatabaseURL == "" {
        return nil, errors.New("DATABASE_URL is required")
    }
    if len(cfg.JWTSecret) < 32 {
        return nil, errors.New("JWT_SECRET must be at least 32 characters")
    }
    return cfg, nil
}

Notice the validation. Fail fast at startup if a required secret is missing or weak. A server that boots without its signing key and then fails on the first login is worse than one that refuses to start.

.env files: convenient, dangerous

For local development, a .env file keeps secrets out of your code:

DATABASE_URL=postgres://app:devpass@localhost:5432/appdb
JWT_SECRET=a-long-random-string-for-local-use-only

The golden rule: add .env to .gitignore before you create it. Then commit a .env.example with placeholder values, so teammates know which variables exist without seeing real ones:

DATABASE_URL=postgres://user:password@localhost:5432/dbname
JWT_SECRET=change-me-to-something-long-and-random

Local secrets should differ from production ones. Your laptop's database password should never also open the live system.

Generating good secrets

Don't type a "random" secret off the top of your head. Humans are predictable. Generate one:

openssl rand -base64 48

Or in Go, with crypto/rand. And never use math/rand for anything security-related. It's predictable by design, a bit like using a loaded die in a casino and hoping nobody checks.

Beyond environment variables

As projects grow, teams move to dedicated secret managers: your cloud provider's secret service, HashiCorp Vault, or the secret stores built into container orchestrators and hosting platforms. They add access control, audit logs, and rotation. The principle is unchanged: secrets live outside the code, are delivered at runtime, and are tightly controlled.

In containers, avoid baking secrets into the image. Anyone who can pull the image can read them. Pass them at runtime through the platform's secret mechanism.

Keep secrets out of logs, too

A sneaky leak path: your own logging. Don't print request bodies on login routes. Don't log full Authorization headers. Don't dump entire config structs at startup with %+v. Implement a String() method on your config that redacts sensitive fields:

func (c Config) String() string {
    return fmt.Sprintf("Config{Port: %s, DatabaseURL: [redacted], JWTSecret: [redacted]}", c.Port)
}

Logs travel: to dashboards, to third-party services, to the screenshots people paste into chat. Assume that anything you log will eventually be read by someone who shouldn't.

What to do when a secret leaks

Not if. When. Have a plan:

  1. Rotate immediately. Issue a new credential and revoke the old one. Deleting the commit is not enough.
  2. Find the blast radius. What could that secret access? Check the logs for suspicious use.
  3. Invalidate dependent tokens. If the JWT signing key leaked, every token ever signed with it is forgeable, so change the key, which logs everyone out. That's inconvenient, and far better than the alternative.
  4. Learn something. Add a secret-scanning step to your CI pipeline so the next one gets caught early.

Common mistakes

Storing passwords with fast hashes. SHA-256 and MD5 are for fingerprints, not passwords.

Inventing your own scheme. "I'll hash it twice and add the username" is how breaches are born. Use bcrypt or Argon2 as designed.

Different error messages for "no user" and "wrong password." One generic message, every time.

Committing .env files. Gitignore first, create second.

Reusing secrets across environments. A leaked dev key shouldn't open production.

Logging sensitive values. Redact, always.

Returning the password hash in API responses. Map to a response struct that never includes it, as we did back in the first article.

Quick recap

  • Never store plain-text passwords. Hash them with a slow, salted algorithm: bcrypt or Argon2id.
  • Hashing is one-way, encryption is two-way, and passwords need the former.
  • Compare with the library's constant-time function, and burn equal time when a user isn't found.
  • Prefer long passwords and breach-list checks over silly composition rules, and rate-limit logins.
  • Keep secrets out of source code. Load them from the environment, validate at startup, and fail fast.
  • Gitignore .env, commit .env.example, and use different secrets per environment.
  • Redact secrets in logs, and know how to rotate when one leaks.
📰 Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.