Skip to content

Hashing

Security

Hashing

Introduction

The laravel::hash module hashes your users' passwords with bcrypt. Bcrypt is a great choice for passwords because you can tune how long a hash takes, and raise it as hardware gets faster. Slow is good when hashing passwords: the longer each guess takes, the longer an attacker needs to crack a stolen hash.

In most applications, you won't need to call this module directly. Authentication verifies and updates password hashes automatically, and create! and update! hash plain passwords assigned to PasswordHash columns. Call hash::make directly when you need a hash outside a model write.

Configuration

By default, Laravel hashes passwords with a bcrypt cost factor of 12. You can adjust the work factor with BCRYPT_ROUNDS, where each increment doubles the hashing time:

1BCRYPT_ROUNDS=12
1BCRYPT_ROUNDS=12

Tests using for_testing automatically hash with fewer rounds to stay fast.

Basic usage

Hashing passwords

You may hash a password by calling make. It returns a PasswordHash to store in your users table. This sign-up handler hashes the password from its form and creates the user:

1use laravel::hash::{self, Password};
2use laravel::model::create;
3use laravel::prelude::*;
4 
5#[laravel::input]
6#[validate(anyone)]
7pub struct SignUp {
8 #[validate(required, max_length(255))]
9 name: String,
10 #[validate(required, email)]
11 email: String,
12 #[validate(required, password, confirmed)]
13 password: Password,
14}
15 
16pub async fn sign_up(Valid(form): Valid<SignUp>) -> laravel::Result<Redirect> {
17 let password = hash::make(&form.password).await?;
18 
19 create!(User { name: &form.name, email: &form.email, password }).await?;
20 
21 Ok(Redirect::to("/login"))
22}
1use laravel::hash::{self, Password};
2use laravel::model::create;
3use laravel::prelude::*;
4 
5#[laravel::input]
6#[validate(anyone)]
7pub struct SignUp {
8 #[validate(required, max_length(255))]
9 name: String,
10 #[validate(required, email)]
11 email: String,
12 #[validate(required, password, confirmed)]
13 password: Password,
14}
15 
16pub async fn sign_up(Valid(form): Valid<SignUp>) -> laravel::Result<Redirect> {
17 let password = hash::make(&form.password).await?;
18 
19 create!(User { name: &form.name, email: &form.email, password }).await?;
20 
21 Ok(Redirect::to("/login"))
22}

Because create! and update! hash plain-text passwords automatically when assigning to a PasswordHash column, the handler above could skip hash::make and pass password: &form.password directly. Call hash::make yourself when you need the hash outside a model operation.

Password fields

Declare password fields in your forms as Password rather than String. Its debug output is Password([redacted]), so the plain-text password stays out of your logs.

Password also enforces bcrypt's length limit. Bcrypt uses only the first 72 bytes of a password, so make rejects longer inputs with a 422 error. A Password field instead fails validation and attaches an error message to that field for display to the user.

Storing hashes

Store a hash in a PasswordHash field. Database queries bind and read it as text, and its debug output is PasswordHash([redacted]):

1use laravel::hash::PasswordHash;
2use laravel::model::model;
3 
4#[model]
5pub struct User {
6 pub id: i64,
7 pub name: String,
8 pub email: String,
9 #[serde(skip)]
10 pub password: PasswordHash,
11}
1use laravel::hash::PasswordHash;
2use laravel::model::model;
3 
4#[model]
5pub struct User {
6 pub id: i64,
7 pub name: String,
8 pub email: String,
9 #[serde(skip)]
10 pub password: PasswordHash,
11}

PasswordHash doesn't implement Serialize, so a JSON response can't include the hash by accident. A struct that derives Serialize must mark the field #[serde(skip)], or it doesn't compile.

Verifying that a password matches a hash

The hash::check function verifies that a given plain-text password matches a stored bcrypt hash, returning false if the password does not match or the hash is malformed:

1use laravel::hash;
2 
3if hash::check(&form.password, &user.password).await {
4 // The passwords match...
5}
1use laravel::hash;
2 
3if hash::check(&form.password, &user.password).await {
4 // The passwords match...
5}

To log a user in, use Auth::attempt instead. It checks the password for you, and takes as long to fail whether or not the account exists.

Determining if a password needs to be rehashed

needs_rehash returns true when a stored hash uses a different cost factor than your current configuration. Rehash the password right after check succeeds while you still have the plain text:

1use laravel::hash;
2 
3if hash::check(&form.password, &user.password).await {
4 if hash::needs_rehash(&user.password) {
5 let password = hash::make(&form.password).await?;
6 // Store the new hash...
7 }
8 
9 // Log the user in...
10}
1use laravel::hash;
2 
3if hash::check(&form.password, &user.password).await {
4 if hash::needs_rehash(&user.password) {
5 let password = hash::make(&form.password).await?;
6 // Store the new hash...
7 }
8 
9 // Log the user in...
10}

Auth::attempt does this for you, so after you raise BCRYPT_ROUNDS, each user's hash upgrades the next time they log in. A new hash also logs the user out of their other devices, so raising the rounds logs each user out of their other devices once.