dust

Hashing

Introduction

The dust::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.

[!NOTE] Bcrypt is deliberately slow, which is right for passwords but wrong for values you look up on every request. For an API token, generate a long random value, show it to the user once, and store a fast SHA-256 hash of it in an indexed column. To store a secret you must read back, such as another service's token, use encryption instead.

Configuration

By default, dust-framework 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:

ini
BCRYPT_ROUNDS=12
Rounds Trade-off
Lower than 12 Faster sign-in and tests, but a stolen hash is cheaper to crack.
12 The default balance between login latency and resistance.
Higher than 12 Stronger against offline cracking, at the cost of slower logins and sign-ups.

Raise the factor as your hardware gets faster. Existing hashes keep working; Auth::attempt upgrades each one on the user's next login, as below explains.

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

Basic usage

Function What it does
hash::make(password) Hashes a plain-text password with the current cost.
hash::check(password, hash) Reports whether the plain text matches the stored hash.
hash::needs_rehash(hash) Reports whether the hash uses an outdated cost factor.

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:

rust
use dust::hash::{self, Password};use dust::model::create;use dust::prelude::*;#[dust::input]#[validate(anyone)]pub struct SignUp {    #[validate(required, max_length(255))]    name: String,    #[validate(required, email)]    email: String,    #[validate(required, password, confirmed)]    password: Password,}pub async fn sign_up(Valid(form): Valid<SignUp>) -> dust::Result<Redirect> {    let password = hash::make(&form.password).await?;    create!(User { name: &form.name, email: &form.email, password }).await?;    Ok(Redirect::to("/login"))}

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]):

rust
use dust::hash::PasswordHash;use dust::model::model;#[model]pub struct User {    pub id: i64,    pub name: String,    pub email: String,    #[serde(skip)]    pub password: PasswordHash,}

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:

rust
use dust::hash;if hash::check(&form.password, &user.password).await {    // The passwords match...}

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:

rust
use dust::hash;if hash::check(&form.password, &user.password).await {    if hash::needs_rehash(&user.password) {        let password = hash::make(&form.password).await?;        // Store the new hash...    }    // Log the user in...}

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.