
# Password encoders

A `PasswordEncoder` turns a password into a hash to store (`encode`) and checks a typed password against a stored hash (`matches`). The recommended one is the delegating encoder of `PasswordEncoderFactories.createDelegatingPasswordEncoder()`: it writes `{argon2}` hashes and reads every supported format, so you can change algorithms without breaking existing passwords.

## Why

Passwords must never be stored as they are, nor with a fast hash: a leaked table of SHA-256 hashes is cracked in hours. A password hash is slow on purpose, salted (two users with the same password get different hashes) and tunable. The formats are Spring Security's, so a Dart service and a Java service can share a user table: hashes made by one verify in the other.

## Example

```dart
// Registration: store the hash, never the password.
final encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
final stored = encoder.encode(form.password); // {argon2}$argon2id$v=19$m=16384,t=2,p=1$...

// A login check (DaoAuthenticationProvider does this for you).
final ok = encoder.matches(typed, stored);
```

To use it everywhere, declare it as a bean; without one, the auto-configuration uses the same delegating encoder anyway:

```dart
@Bean()
PasswordEncoder passwordEncoder() => PasswordEncoderFactories.createDelegatingPasswordEncoder();
```

## The interface

| Method | Meaning |
|---|---|
| `encode(raw)` | A hash with a new random salt: two calls give different texts that both match. Slow: never in a loop on a request path. |
| `matches(raw, encoded)` | Whether `raw` is the password. `false` for an empty `raw` (an empty password never logs in) and for a missing, empty or malformed hash, as in Spring Security 7. The comparison takes the same time wherever the hashes differ. |
| `upgradeEncoding(encoded)` | Whether the hash was made with weaker settings and should be replaced. |

## The encoders

| Encoder | Id | Defaults (`defaultsForSpringSecurity()`) |
|---|---|---|
| `Argon2PasswordEncoder` | `{argon2}` | Argon2id, 16 MiB of memory, 2 passes, 1 lane, 16-byte salt, 32-byte hash |
| `Pbkdf2PasswordEncoder` | `{pbkdf2}` | HMAC-SHA256, 310 000 iterations, 16-byte salt, 256-bit hash, no secret |
| `SCryptPasswordEncoder` | `{scrypt}` | N = 65 536, r = 8, p = 1, 32-byte hash, 16-byte salt |
| `NoOpPasswordEncoder` | `{noop}` | the password as it is: development only |
| `DelegatingPasswordEncoder` | | prefixes each hash with `{id}` and checks it with that id's encoder |

The defaults are Spring Security's `defaultsForSpringSecurity_v5_8` for each algorithm.

### Your own settings

```dart
final argon2 = Argon2PasswordEncoder(
  saltLength: 16,
  hashLength: 32,
  parallelism: 1,
  memory: 65536,       // KiB: the main cost knob
  iterations: 3,
);

final pbkdf2 = Pbkdf2PasswordEncoder(
  saltLength: 16,
  iterations: 600000,
  secret: pepper,                                 // a value kept outside the user table
  algorithm: Pbkdf2Algorithm.pbkdf2WithHmacSha512,
);

final scrypt = SCryptPasswordEncoder(
  cpuCost: 32768,      // a power of two up to 65 536
  memoryCost: 8,
  parallelization: 1,
  keyLength: 32,
  saltLength: 16,
);
```

- Argon2 refuses a salt below 8 bytes, a hash below 16, a parallelism or iterations below 1, and memory below 8 KiB per lane.
- PBKDF2's hash does not say which settings made it: an encoder can only check hashes made with its own settings, and `upgradeEncoding` cannot detect weak ones. `secret` is a pepper appended to the salt, as in Spring.
- scrypt refuses a stored hash with a cost above 65 536 or a hash longer than 256 bytes, so a corrupted hash cannot make one login run for long.

## The delegating encoder

`PasswordEncoderFactories.createDelegatingPasswordEncoder()` writes `{argon2}` hashes with Spring's defaults and checks `{argon2}`, `{pbkdf2}`, `{scrypt}`, their `@SpringSecurity_v5_8` variants (`{pbkdf2@SpringSecurity_v5_8}`) and `{noop}`.

Build one to choose the ids yourself:

```dart
final encoder = DelegatingPasswordEncoder('argon2', {
  'argon2': Argon2PasswordEncoder.defaultsForSpringSecurity(),
  'noop': const NoOpPasswordEncoder(),
});
```

- A stored hash without an `{id}`, or with an id no encoder has, makes `matches` throw an `ArgumentError`, unless `defaultPasswordEncoderForMatches` is set: a configuration error, not a wrong password. `DaoAuthenticationProvider` refuses the login.
- `{bcrypt}` hashes get an error message of their own: BCrypt is not available.
- `upgradeEncoding` reports every hash of another id, so the login re-hashes it.

## Upgrading hashes at login

After a successful login, `DaoAuthenticationProvider` asks `upgradeEncoding`. When the stored hash was made with another `{id}` or weaker parameters, it hashes the typed password again with the current settings and stores it through the `UserDetailsPasswordService` bean (or the `UserDetailsService` itself when it is one). Raise the cost over the years, and users move to it as they log in.

## Hashes shared with Java

Argon2, PBKDF2 and scrypt use Bouncy Castle's Dart port (`pointycastle`), like Spring's Java encoders, and their hashes verify both ways (checked against Spring Security 7.1). One exception: in the delegating encoder, `{pbkdf2}` means the `@SpringSecurity_v5_8` settings here, while Spring 6 and later read it with the older v5_5 settings. Java hashes stored as `{pbkdf2}` may therefore not verify here; `{pbkdf2@SpringSecurity_v5_8}` hashes do.

## In Spring (Java)

```java
PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
```

Spring's default id is `bcrypt`. BCrypt is not here: there is no vetted Dart implementation, and cryptography is not written by hand in this project. New hashes are `{argon2}`, which Spring checks too.

## See also

- [Authentication](authentication.md)
- [Differences from Spring](differences.md)
