Password hashing and random secrets

You can hash passwords without storing plaintext and generate opaque refresh-token values for the authentication endpoints.

Learning outcomes

  • Explain why bcrypt's salted, configurable computational cost makes password guessing more expensive than using SHA-256.
  • Understand how bcrypt stores its algorithm version, cost and salt in the password hash.
  • Enforce bcrypt's 72-byte password limit and reduce user enumeration with a dummy hash.
  • Generate 32 cryptographically secure random bytes and encode them as 64 lowercase hexadecimal characters.

When someone signs up for the food-delivery API, you need to store enough information to verify their password during a later login. You must not store the original password. You also need to generate refresh tokens that clients can present later, and those tokens must be difficult to guess.

These are two different problems. Passwords come from users and need a secure verification mechanism. Refresh tokens come from your server and need unpredictable random values.

Password verification instead of recovery

You do not need to recover a user's password. You only need to determine whether a password supplied during login matches the one they registered with.

Storing plaintext passwords makes a database breach immediately dangerous. Encrypting passwords does not solve the problem because encryption is reversible by someone who possesses the decryption key.

Password hashing gives you a different approach. During signup, you transform the password into a stored hash. During login, you verify the candidate password against that stored hash.

The original password is not needed after signup.

The problem with SHA-256

SHA-256 is a cryptographic hash function designed to calculate digests quickly. That makes it useful for integrity checks and other cryptographic operations, but unsuitable for storing passwords.

Imagine an attacker obtains a copy of your users table. They can repeatedly hash guessed passwords and compare the results with the stored values.

Even adding a random salt to SHA-256 does not make each password guess expensive. A salt prevents identical passwords from producing identical hashes and makes precomputed rainbow-table attacks less useful. The attacker can still test individual guesses quickly.

Password storage needs an algorithm that deliberately makes each guess computationally expensive.

bcrypt and adaptive cost

bcrypt is an adaptive password-hashing algorithm. It generates a random salt for each password and performs computational work when hashing or verifying it.

The salt means two users who choose the same password receive different stored hashes. The cost parameter controls how much work bcrypt performs.

In Go, the golang.org/x/crypto/bcrypt package provides the hashing and verification functions:

go
hash, err := bcrypt.GenerateFromPassword(
    []byte(password),
    12,
)
if err != nil {
    return "", err
}
storedHash := string(hash)

The example uses cost 12. The W3B1 grading tests require a cost of at least 10, and the reference implementation uses 12.

Increasing the cost by one approximately doubles the computational work. This makes repeated password guessing more expensive, but also makes legitimate login requests slower.

The stored bcrypt hash

A bcrypt hash contains the information needed for later verification. You do not need a separate database column for the salt.

A typical bcrypt hash has this structure:

$2a$12$<22-character-salt><31-character-hash>
ComponentMeaning
$2a$bcrypt algorithm version
12Configured computational cost
22 charactersEncoded random salt
31 charactersEncoded password hash

The complete bcrypt representation is 60 characters long.

The users.password_hash column stores this entire value. During login, bcrypt reads the algorithm version, cost and salt from the stored hash, then uses them to verify the candidate password.

This is why generating a new bcrypt hash during login and comparing the two strings does not work. A new hash gets a new random salt, so even the correct password produces a different encoded string.

Use CompareHashAndPassword instead:

go
err := bcrypt.CompareHashAndPassword(
    []byte(storedHash),
    []byte(candidate),
)
matches := err == nil

A nil error means the supplied password matches the stored hash. A non-nil error means verification failed.

Choosing a cost

The cost determines how much computational work bcrypt performs. A higher value makes both password hashing and verification slower.

For this course, cost 12 provides a concrete setting above the tested minimum of 10.

The right production cost depends on your deployment hardware. A setting that works on a development laptop may make login too slow when many requests arrive concurrently.

You can benchmark the hashing operation with a Go benchmark:

go
func BenchmarkHashPassword(b *testing.B) {
    for i := 0; i < b.N; i++ {
        _, err := bcrypt.GenerateFromPassword(
            []byte("benchmark-password"), 12,
        )
        if err != nil {
            b.Fatal(err)
        }
    }
}

Run the benchmark from the backend module:

bash
go test -bench=. -benchmem ./internal/auth

Notice that bcrypt consumes CPU during login as well as signup. You should account for concurrent authentication requests when choosing a production cost.

The 72-byte password limit

Bcrypt supports passwords up to 72 bytes. This is a byte limit, not a character limit.

Go strings contain UTF-8 encoded bytes. An ASCII character occupies one byte, while some Unicode characters occupy multiple bytes.

For example, an ASCII password containing 73 characters occupies 73 bytes. A password containing fewer Unicode characters can also exceed 72 bytes.

Measure the encoded byte length:

go
passwordBytes := []byte(password)
passwordLength := len(passwordBytes)

For W3B1, signup passwords must contain between 1 and 72 bytes. An empty password and a password consisting of 73 a characters must be rejected.

The same byte limit should apply during login. Otherwise, signup and login could interpret the accepted password differently.

Consistent login failures

Password verification also affects what an attacker can discover about your users.

Consider two login requests:

  • One uses an email address that does not exist.
  • The other uses a registered email address with an incorrect password.

Returning different responses reveals which email addresses have accounts. This is called user enumeration.

The W3B1 contract requires both requests to return HTTP 401 with error invalid_credentials.

That gives the client one generic authentication failure instead of revealing whether the email or password was incorrect.

Timing differences

Using the same response body does not necessarily make the two requests behave alike.

Consider the internal work performed by each request:

Unknown email:
    Query users
    Return 401

Registered email, wrong password:
    Query users
    Run bcrypt comparison
    Return 401

Bcrypt is deliberately computationally expensive. The difference in processing time can reveal whether an account exists even when both responses contain the same error.

A common mitigation is a precomputed dummy bcrypt hash.

Generate the dummy hash ahead of time using the same cost as real password hashes. When the email does not exist, compare the submitted password against that dummy hash instead of returning immediately.

The decision can be represented by this small fragment:

go
hashToCheck := dummyHash
if accountFound {
    hashToCheck = storedHash
}

err := bcrypt.CompareHashAndPassword(
    []byte(hashToCheck),
    []byte(password),
)

Both paths now perform a bcrypt comparison. You still return the same generic authentication failure when the account is unknown or the password is incorrect.

The dummy hash does not represent a real account. It exists to make the verification paths more comparable.

This reduces an obvious timing difference, but it does not guarantee identical request durations. Database access, scheduling and other operations can still affect timing.

The database error path also needs separate handling. A database outage is a server failure, not an invalid password.

Cryptographically secure random values

A refresh token is different from a password. Your server generates it instead of asking a user to choose it.

An attacker who obtains a refresh token may be able to use it to obtain a new access token. Its value must therefore be unpredictable.

Use crypto/rand for authentication secrets. Do not use math/rand, which is intended for non-security-sensitive random values such as simulations and sampling.

crypto/rand obtains cryptographically secure random values from the operating system.

Randomness and token size

For this project, generate 32 random bytes.

32 bytes × 8 bits = 256 bits

That gives you 2^256 possible values. Guessing a correctly generated token by brute force is infeasible.

The random bytes are not convenient to transmit directly as a string. Encode them as hexadecimal instead.

Each byte becomes two hexadecimal characters:

32 random bytes are encoded as hexadecimal, producing 64 lowercase hexadecimal characters.

The encoding changes the representation, not the amount of randomness. Your token still contains 256 bits of entropy.

In Go, the relevant operations are:

go
raw := make([]byte, 32)
_, err := rand.Read(raw)
// Handle an error before using raw.
token := hex.EncodeToString(raw)

The crypto/rand package supplies the random bytes. The encoding/hex package converts them into a printable hexadecimal string.

Check errors from the random source before using the generated value. A refresh token must never be issued from an unsuccessful random read.

Refresh tokens as credentials

A refresh token is a bearer credential. Anyone possessing it can potentially exchange it for a new token pair.

Unlike a password, the user does not need to remember or choose this value. The server generates it and returns it to the client.

The authentication service stores an association between the refresh token and the account in Redis. This allows the service to identify the account when the client presents the token again.

Keep the refresh token separate from the access token. The access token is a signed JWT used to authenticate API requests. The refresh token is an opaque value used to obtain replacement credentials.

The distinction matters because the two credentials have different formats and responsibilities. A refresh token is not a JWT, and hexadecimal encoding does not make it a signed token.

Passwords and secrets in signup and login

The users table provides the persistent account record for the authentication endpoints.

Its password_hash column stores the bcrypt output. The account's email and role identify the account, while restaurant_id can associate a restaurant account with a restaurant.

The important boundary is what reaches MySQL:

ValueStorage or handling
User's original passwordUsed for verification, never stored
Bcrypt outputStored in users.password_hash
Bcrypt saltEmbedded in the stored hash
Refresh tokenGenerated by the server and associated with a user in Redis

During signup, the API validates the password length and hashes the password before storing the account. During login, it retrieves the stored hash and verifies the submitted password against it.

The W3B1 exercise checks that the stored value has the bcrypt hash format and a cost of at least 10. It also checks that an unknown email and a wrong password both produce 401 invalid_credentials.

The same exercise uses cryptographically secure random bytes to generate refresh tokens. The expected representation is 64 lowercase hexadecimal characters, produced from 32 random bytes.

These boundaries keep password verification separate from token generation. One protects credentials chosen by users. The other creates credentials that only your server should generate.

Check your understanding

Question 1 of 4

Two accounts register with the same password. Their users.password_hash values are different. What explains this?

Pick an answer, then say how sure you are.

References

Everything above is explained on this page; these are where it comes from (Go 1.25, golang.org/x/crypto/bcrypt).

Finished Lesson 3.1?