Password hashing

suggest change

A password hash lets a server check a password without storing it. The Authentication article shows a compact Argon2id helper and how it fits into a login flow, and the Cryptography article introduces Argon2id alongside other primitives. This article goes deeper into the hashing itself:

Packages used:

dart pub add cryptography crypto bcrypt unorm_dart

The examples were run with Dart 3.13, cryptography 2.9.0, crypto 3.0.7, bcrypt 1.2.0 and unorm_dart 0.3.3. Reference hashes were made with Python's argon2-cffi 25.1 and bcrypt 5.0. All timings come from one machine and are only useful for comparing settings with each other. Measure on your own servers.

Why a fast hash is the wrong tool

Password hashing protects you when the database leaks. If the table holds plain SHA-256 hashes, two things go wrong at once:

import 'dart:convert';

import 'package:crypto/crypto.dart';

void main() {
  // A leaked table of unsalted SHA-256 password hashes.
  final leaked = {
    'alice': sha256.convert(utf8.encode('sunshine1')).toString(),
    'bob': sha256.convert(utf8.encode('dragon2024')).toString(),
    'carol': sha256.convert(utf8.encode('sunshine1')).toString(),
  };
  print('alice == carol: ${leaked['alice'] == leaked['carol']}');

  // The attacker hashes a word list once and looks every user up.
  final words = ['123456', 'password', 'dragon2024', 'qwerty', 'sunshine1'];
  final table = {
    for (final w in words) sha256.convert(utf8.encode(w)).toString(): w,
  };
  for (final MapEntry(:key, :value) in leaked.entries) {
    print('$key: ${table[value] ?? '?'}');
  }

  // How many guesses per second does one core manage?
  const n = 1000000;
  final sw = Stopwatch()..start();
  for (var i = 0; i < n; i++) {
    sha256.convert(utf8.encode('guess$i'));
  }
  final perSec = n * 1000 ~/ sw.elapsedMilliseconds;
  print('SHA-256 guesses per second: $perSec');
}

Output:

alice == carol: true
alice: sunshine1
bob: dragon2024
carol: sunshine1
SHA-256 guesses per second: 603136

A password hash fixes both problems:

Algorithm Status Notes
Argon2id recommended (RFC 9106, OWASP) memory-hard, no input length limit
scrypt acceptable memory-hard
bcrypt acceptable for existing systems uses only the first 72 bytes of the password
PBKDF2-HMAC-SHA256 when FIPS compliance is required not memory-hard, needs 600,000+ iterations
SHA-256, SHA-1, MD5 (even salted) never too fast

Argon2id parameters

Argon2id fills a block of memory with pseudo-random data derived from the password and salt, then reads it back in a data-dependent order. It has three knobs:

OWASP lists five configurations of roughly equal strength, all with p=1: m=47104,t=1, m=19456,t=2, m=12288,t=3, m=9216,t=4 and m=7168,t=5. RFC 9106 suggests m=65536,t=3,p=4 when memory is plentiful. Which one to use depends on how fast it runs on your hardware, so measure:

import 'package:cryptography/cryptography.dart';

/// Median time in milliseconds of [runs] Argon2id hashes.
Future<int> timeArgon2(int m, int t, int p, {int runs = 5}) async {
  final algo = Argon2id(
    memory: m,
    iterations: t,
    parallelism: p,
    hashLength: 32,
  );
  final salt = List<int>.filled(16, 7);
  final times = <int>[];
  for (var i = 0; i < runs; i++) {
    final sw = Stopwatch()..start();
    await algo.deriveKeyFromPassword(password: 'benchmark', nonce: salt);
    times.add(sw.elapsedMilliseconds);
  }
  times.sort();
  return times[runs ~/ 2];
}

Future<void> main() async {
  await timeArgon2(1024, 1, 1, runs: 3); // warm up the JIT

  // The five equivalent OWASP configurations (m in KiB).
  const owasp = [(47104, 1), (19456, 2), (12288, 3), (9216, 4), (7168, 5)];
  print('    m (KiB)  t  p   ms');
  for (final (m, t) in owasp) {
    print(
      '${'$m'.padLeft(11)}  $t  1  ${'${await timeArgon2(m, t, 1)}'.padLeft(3)}',
    );
  }
  // Stronger settings.
  for (final (m, t, p) in [(65536, 3, 1), (65536, 3, 4)]) {
    print(
      '${'$m'.padLeft(11)}  $t  $p  ${'${await timeArgon2(m, t, p)}'.padLeft(3)}',
    );
  }
}

Output on the machine used for this article:

    m (KiB)  t  p   ms
      47104  1  1  446
      19456  2  1  255
      12288  3  1  211
       9216  4  1  194
       7168  5  1  215
      65536  3  1  989
      65536  3  4  481

How to read this:

A sensible default for a pure-Dart server is the OWASP m=19456,t=2,p=1. Raise memory if your servers have it.

A reusable PasswordHasher

The helpers in the other articles compare the stored string with a fixed prefix and trust the parsed numbers. A stricter version:

Save it as bin/hasher.dart. The later examples import it.

import 'dart:convert';
import 'dart:isolate';
import 'dart:math';

import 'package:cryptography/cryptography.dart';
import 'package:unorm_dart/unorm_dart.dart' as unorm;

/// A parsed `$argon2id$v=19$m=...,t=...,p=...$salt$hash` string.
class PhcHash {
  PhcHash(
    this.memoryKiB,
    this.iterations,
    this.parallelism,
    this.salt,
    this.hash,
  );

  final int memoryKiB, iterations, parallelism;
  final List<int> salt, hash;

  static final _re = RegExp(
    r'^\$argon2id\$v=19\$m=(\d{1,7}),t=(\d{1,3}),p=(\d{1,2})'
    r'\$([A-Za-z0-9+/]{11,64})\$([A-Za-z0-9+/]{22,86})$',
  );

  /// Parses [s], rejecting anything malformed or absurdly expensive.
  factory PhcHash.parse(String s) {
    final m = _re.firstMatch(s);
    if (m == null) throw FormatException('not an argon2id v19 PHC string');
    final (mem, t, p) = (int.parse(m[1]!), int.parse(m[2]!), int.parse(m[3]!));
    if (mem > 1 << 20 || t < 1 || t > 20 || p < 1 || mem < 8 * p) {
      throw FormatException('argon2id parameters out of range: $mem,$t,$p');
    }
    return PhcHash(mem, t, p, _unb64(m[4]!), _unb64(m[5]!));
  }

  @override
  String toString() =>
      '\$argon2id\$v=19\$m=$memoryKiB,t=$iterations,'
      'p=$parallelism\$${_b64(salt)}\$${_b64(hash)}';
}

String _b64(List<int> b) => base64.encode(b).replaceAll('=', '');
List<int> _unb64(String s) => base64.decode(base64.normalize(s));

class PasswordHasher {
  PasswordHasher({
    this.memoryKiB = 19456,
    this.iterations = 2,
    this.parallelism = 1,
    this.maxPasswordLength = 1024,
  });

  final int memoryKiB, iterations, parallelism, maxPasswordLength;

  Future<String> hash(String password) async {
    final rng = Random.secure();
    final salt = List<int>.generate(16, (_) => rng.nextInt(256));
    final bytes = await _argon2(
      _prepare(password),
      salt,
      memoryKiB,
      iterations,
      parallelism,
      32,
    );
    return PhcHash(memoryKiB, iterations, parallelism, salt, bytes).toString();
  }

  /// Returns false for a wrong password and for a malformed [stored] string.
  Future<bool> verify(String password, String stored) async {
    final PhcHash phc;
    try {
      phc = PhcHash.parse(stored);
    } on FormatException {
      return false;
    }
    final actual = await _argon2(
      _prepare(password),
      phc.salt,
      phc.memoryKiB,
      phc.iterations,
      phc.parallelism,
      phc.hash.length,
    );
    return Mac(actual) == Mac(phc.hash); // constant-time comparison
  }

  /// True if [stored] is weaker than the current settings (or unparseable).
  bool needsRehash(String stored) {
    try {
      final phc = PhcHash.parse(stored);
      return phc.memoryKiB < memoryKiB ||
          phc.iterations < iterations ||
          phc.salt.length < 16 ||
          phc.hash.length < 32;
    } on FormatException {
      return true;
    }
  }

  List<int> _prepare(String password) {
    if (password.length > maxPasswordLength) {
      throw ArgumentError('password longer than $maxPasswordLength');
    }
    // Same password typed on different keyboards must give the same bytes.
    return utf8.encode(unorm.nfc(password));
  }
}

Future<List<int>> _argon2(
  List<int> password,
  List<int> salt,
  int m,
  int t,
  int p,
  int length,
) => Isolate.run(() async {
  final algo = Argon2id(
    memory: m,
    iterations: t,
    parallelism: p,
    hashLength: length,
  );
  final key = await algo.deriveKey(secretKey: SecretKey(password), nonce: salt);
  return key.extractBytes();
});

A quick check:

import 'hasher.dart';

Future<void> main() async {
  final hasher = PasswordHasher();
  final stored = await hasher.hash('correct horse battery staple');
  print(stored);
  print(
    'right:     ${await hasher.verify('correct horse battery staple', stored)}',
  );
  print(
    'wrong:     ${await hasher.verify('correct horse battery stapler', stored)}',
  );
  print('garbage:   ${await hasher.verify('x', r'$2b$10$abc')}');

  final phc = PhcHash.parse(stored);
  print(
    'm=${phc.memoryKiB} t=${phc.iterations} p=${phc.parallelism} '
    'salt=${phc.salt.length}B hash=${phc.hash.length}B',
  );

  print('rehash current: ${hasher.needsRehash(stored)}');
  final stronger = PasswordHasher(memoryKiB: 47104, iterations: 1);
  print('rehash for m=47104,t=1: ${stronger.needsRehash(stored)}');

  try {
    PhcHash.parse(
      r'$argon2id$v=19$m=9999999,t=1,p=1$c2FsdHNhbHRzYWx0$'
      'aGFzaGhhc2hoYXNoaGFzaGhhc2g',
    );
  } on FormatException catch (e) {
    print(e.message);
  }
}

Output (the salt and hash change on every run):

$argon2id$v=19$m=19456,t=2,p=1$Y4fDCrP4qmYKVJiWjJJ+/g$bcEo3h8fN038d0u/c0y/yyGhpcm1F13n+ClGR499G9A
right:     true
wrong:     false
garbage:   false
m=19456 t=2 p=1 salt=16B hash=32B
rehash current: false
rehash for m=47104,t=1: true
argon2id parameters out of range: 9999999,1,1

Details worth knowing:

Unicode normalization

The same visible password can arrive as different bytes. Depending on the operating system and keyboard, "café" can be typed with a precomposed é or with e followed by a combining accent:

import 'dart:convert';

import 'package:unorm_dart/unorm_dart.dart' as unorm;

void main() {
  // "café" typed two ways: precomposed é (U+00E9) vs e + combining acute (U+0301).
  final mac = String.fromCharCodes([0x63, 0x61, 0x66, 0xE9]);
  final linux = String.fromCharCodes([0x63, 0x61, 0x66, 0x65, 0x301]);
  print('$mac == $linux: ${mac == linux}');
  print('utf8: ${utf8.encode(mac)} vs ${utf8.encode(linux)}');
  print('after NFC equal: ${unorm.nfc(mac) == unorm.nfc(linux)}');
  print('NFC bytes: ${utf8.encode(unorm.nfc(linux))}');
}

Output:

café == café: false
utf8: [99, 97, 102, 195, 169] vs [99, 97, 102, 101, 204, 129]
after NFC equal: true
NFC bytes: [99, 97, 102, 195, 169]

Without normalization, a user who registered on one device may not be able to log in from another. NIST SP 800-63B recommends normalizing to NFC or NFKC before hashing. The Dart SDK has no normalization function, so PasswordHasher uses package:unorm_dart. Pick one form and never change it, because changing it breaks existing hashes of non-ASCII passwords. See Unicode and encodings for more on code points and combining characters.

Compatibility with other languages

PasswordHasher reads and writes standard PHC strings, so hashes move freely between Dart and Argon2 libraries in other languages. This hash was made by Python's argon2-cffi with its default settings:

import 'hasher.dart';

Future<void> main() async {
  // Made by Python's argon2-cffi with its defaults (m=64 MiB, t=3, p=4).
  const fromPython =
      r'$argon2id$v=19$m=65536,t=3,p=4$vDOb2YDX8ji8qCPyY7GA2Q'
      r'$CydfQxcvVm6APzd4JL7BZoGx6B53Wz1FeQN+4FQUejQ';
  final hasher = PasswordHasher();
  final sw = Stopwatch()..start();
  print(await hasher.verify('correct horse battery staple', fromPython));
  print('${sw.elapsedMilliseconds} ms');
  print(hasher.needsRehash(fromPython));
  print(await hasher.hash('hello from dart'));
}

Output:

true
339 ms
false
$argon2id$v=19$m=19456,t=2,p=1$LsNwcj2WvFu+R+zs9unTiQ$JSUIIehRj26Iai6RwHERBV64/h+uNGZg3VWfKLyE3Sc

And in the other direction, in Python:

>>> import argon2
>>> argon2.PasswordHasher().verify('$argon2id$v=19$m=19456,t=2,p=1$LsNwcj2WvFu+R+zs9unTiQ$JSUIIehRj26Iai6RwHERBV64/h+uNGZg3VWfKLyE3Sc', 'hello from dart')
True

The Python hash isn't flagged for rehash, because it uses more memory and more iterations than the Dart settings. A hash made by another implementation is also a good test vector. It catches a broken or misused implementation cheaply (see Testing below).

Adding a pepper

A pepper is a secret key mixed into every hash and stored outside the database: in an environment variable, a secrets manager or an HSM. If only the database leaks, the attacker can't test guesses at all. A pepper doesn't help if the whole server is compromised, and if you lose it, every stored password is lost with it.

There are two common ways to add one:

import 'dart:convert';

import 'package:cryptography/cryptography.dart' hide Hmac;
import 'package:crypto/crypto.dart' show Hmac, sha256;

final algo = Argon2id(
  memory: 19456,
  iterations: 2,
  parallelism: 1,
  hashLength: 32,
);

String hex(List<int> b) =>
    b.map((x) => x.toRadixString(16).padLeft(2, '0')).join();

Future<void> main() async {
  final password = utf8.encode('correct horse battery staple');
  // A fixed salt, only so the output can be compared with another library.
  final salt = List<int>.filled(16, 7);
  final pepper = utf8.encode('server-side pepper 0123456789abc');

  // Option 1: Argon2's built-in secret input (the "K" parameter).
  final withSecret = await algo.deriveKey(
    secretKey: SecretKey(password),
    nonce: salt,
    optionalSecret: pepper,
  );
  print('argon2 secret: ${hex(await withSecret.extractBytes())}');

  final without = await algo.deriveKey(
    secretKey: SecretKey(password),
    nonce: salt,
  );
  print('no pepper:     ${hex(await without.extractBytes())}');

  // Option 2: HMAC the password with the pepper, then hash the result.
  final mac = Hmac(sha256, pepper).convert(password).bytes;
  final withHmac = await algo.deriveKey(secretKey: SecretKey(mac), nonce: salt);
  print('hmac first:    ${hex(await withHmac.extractBytes())}');
}

Output:

argon2 secret: b9f8c9c90bb0a209bf76395450779b4d579dd60c8856be0bb3bf44a728931700
no pepper:     799f12b9e17710824482d829835acb69f5a9355bf774c4f07342823b11b90928
hmac first:    412043f899eb3fceb911b76ec9a9b07566affd93d1736fea6334a931d0224de3

The PHC string has no standard field for "which pepper", so to rotate peppers, store a pepper version in its own column. When a user with an old version logs in, verify with the old pepper and rehash with the new one.

Migrating from older hashes

Long-lived systems collect hash formats. The pattern is always the same: verify with whatever algorithm made the stored hash, and if it isn't the current one, rehash the password the user just typed. You can verify hashes made by Django (PBKDF2), Rails or PHP (bcrypt) directly in Dart:

import 'package:bcrypt/bcrypt.dart';

void main() {
  // Made by Python's bcrypt package with cost 12.
  const stored =
      r'$2b$12$z1J0rlYl8vQX3gZBOb0KauCW4G0i2hsUYkqlXNMrq0FtFd8IZgmP.';
  final sw = Stopwatch()..start();
  print(BCrypt.checkpw('correct horse battery staple', stored));
  print('${sw.elapsedMilliseconds} ms');
  print(BCrypt.checkpw('Correct horse battery staple', stored));

  final mine = BCrypt.hashpw(
    's3cret',
    BCrypt.gensalt(prefix: r'$2b', logRounds: 12),
  );
  print(mine);

  // bcrypt only uses the first 72 bytes; this package refuses longer input.
  try {
    BCrypt.hashpw('a' * 73, BCrypt.gensalt());
  } on ArgumentError catch (e) {
    print(e.message);
  }
}

Output:

true
275 ms
false
$2b$12$iB1pjV2qVYC4MDvTBSFaUOrEycUX/ek7YjZcJPjOHwuOzVdjDmPom
Password is too long (The length should be less than or equal to 72)

The bcrypt string encodes the variant (2a, 2b, 2y), the cost (12 means 2^12 rounds) and a 22-character salt in bcrypt's own Base64 alphabet. The hash made here verifies in Python's bcrypt too. Many other implementations silently ignore everything after byte 72, which makes two long passwords with the same prefix equal. That's one more reason to migrate.

Here is a complete login function that understands bcrypt, Django-style PBKDF2, Argon2id, and unsalted SHA-1 hashes from a very old system:

import 'dart:convert';
import 'dart:isolate';

import 'package:bcrypt/bcrypt.dart';
import 'package:crypto/crypto.dart' show sha1;
import 'package:cryptography/cryptography.dart';

import 'hasher.dart';

final hasher = PasswordHasher();

String _sha1Hex(String s) => sha1.convert(utf8.encode(s)).toString();

/// Checks [password] against any hash format this app has ever stored.
Future<bool> verifyAny(String password, String stored) async {
  if (stored.startsWith(r'$argon2id$')) {
    return hasher.verify(password, stored);
  }
  if (RegExp(r'^\$2[aby]\$\d\d\$').hasMatch(stored)) {
    if (utf8.encode(password).length > 72) return false;
    return Isolate.run(() => BCrypt.checkpw(password, stored));
  }
  if (stored.startsWith(r'pbkdf2_sha256$')) {
    return _checkPbkdf2(password, stored);
  }
  if (stored.startsWith('sha1+')) {
    // An old unsalted SHA-1 hash, wrapped in Argon2id (see wrapAll below).
    return hasher.verify(_sha1Hex(password), stored.substring(5));
  }
  return false;
}

/// Django-style `pbkdf2_sha256$iterations$salt$base64hash`.
Future<bool> _checkPbkdf2(String password, String stored) async {
  final [_, iter, salt, b64] = stored.split(r'$');
  final expected = base64.decode(b64);
  final actual = await Isolate.run(() async {
    final kdf = Pbkdf2(
      macAlgorithm: Hmac.sha256(),
      iterations: int.parse(iter),
      bits: expected.length * 8,
    );
    final key = await kdf.deriveKey(
      secretKey: SecretKey(utf8.encode(password)),
      nonce: utf8.encode(salt),
    );
    return key.extractBytes();
  });
  return Mac(actual) == Mac(expected);
}

/// Offline job: protect unsalted SHA-1 hashes now, without waiting for logins.
Future<void> wrapAll(Map<String, String> db) async {
  for (final MapEntry(:key, :value) in db.entries.toList()) {
    if (RegExp(r'^[0-9a-f]{40}$').hasMatch(value)) {
      db[key] = 'sha1+${await hasher.hash(value)}';
    }
  }
}

Future<bool> login(Map<String, String> db, String user, String password) async {
  final stored = db[user];
  if (stored == null || !await verifyAny(password, stored)) return false;
  if (hasher.needsRehash(stored)) {
    db[user] = await hasher.hash(password); // the only time we have it
    print('  upgraded $user');
  }
  return true;
}

Future<void> main() async {
  final db = {
    'ann': r'$2b$12$z1J0rlYl8vQX3gZBOb0KauCW4G0i2hsUYkqlXNMrq0FtFd8IZgmP.',
    'ben':
        r'pbkdf2_sha256$870000$Xq8Zc1vKpL0mNw4RtY7uAb$'
        'GOH43uPPOE/JTN0dUhx1zCdld1EAApdhcNs7KhIBFUo=',
    'cat': 'b7a875fc1ea228b9061041b7cec4bd3c52ab3ce3', // sha1('letmein')
    'dan': await hasher.hash('dan-pass'),
  };

  await wrapAll(db);
  print('cat after wrapAll: ${db['cat']!.substring(0, 40)}...');

  for (final (user, pw) in [
    ('ann', 'wrong'),
    ('ann', 'correct horse battery staple'),
    ('ben', 'correct horse battery staple'),
    ('cat', 'letmein'),
    ('dan', 'dan-pass'),
  ]) {
    print('$user/$pw: ${await login(db, user, pw)}');
  }
  for (final MapEntry(:key, :value) in db.entries) {
    print('$key: ${value.substring(0, 32)}...');
  }
  print('cat again: ${await login(db, 'cat', 'letmein')}');
}

Output:

cat after wrapAll: sha1+$argon2id$v=19$m=19456,t=2,p=1$hGUt...
ann/wrong: false
  upgraded ann
ann/correct horse battery staple: true
  upgraded ben
ben/correct horse battery staple: true
  upgraded cat
cat/letmein: true
dan/dan-pass: true
ann: $argon2id$v=19$m=19456,t=2,p=1$d...
ben: $argon2id$v=19$m=19456,t=2,p=1$1...
cat: $argon2id$v=19$m=19456,t=2,p=1$7...
dan: $argon2id$v=19$m=19456,t=2,p=1$S...
cat again: true

Limiting concurrent hashes

Each Argon2id hash with m=19456 allocates 19 MiB and keeps a core busy for a few hundred milliseconds. If 64 login requests arrive together and all of them start hashing at once, every one finishes late and memory spikes. A small limiter queues the excess:

import 'dart:async';
import 'dart:collection';
import 'dart:io';

import 'hasher.dart';

/// Lets at most [max] tasks run at once; the rest wait in FIFO order.
class Limiter {
  Limiter(this.max);
  final int max;
  int _running = 0;
  final _waiting = Queue<Completer<void>>();

  Future<T> run<T>(Future<T> Function() task) async {
    if (_running >= max) {
      final c = Completer<void>();
      _waiting.add(c);
      await c.future;
    }
    _running++;
    try {
      return await task();
    } finally {
      _running--;
      if (_waiting.isNotEmpty) _waiting.removeFirst().complete();
    }
  }
}

Future<void> burst(String label, int n, Future<String> Function() hash) async {
  final sw = Stopwatch()..start();
  final done = <int>[];
  await Future.wait([
    for (var i = 0; i < n; i++)
      hash().then((_) => done.add(sw.elapsedMilliseconds)),
  ]);
  print(
    '$label: first done ${done.first} ms, last ${done.last} ms, '
    'peak RSS ${ProcessInfo.maxRss >> 20} MiB',
  );
}

Future<void> main(List<String> args) async {
  final hasher = PasswordHasher();
  final cores = Platform.numberOfProcessors;
  print('logical processors: $cores');
  await hasher.hash('warm up');
  if (args.contains('limited')) {
    final limiter = Limiter(cores ~/ 2);
    await burst(
      '64 logins, ${cores ~/ 2} at a time',
      64,
      () => limiter.run(() => hasher.hash('pw')),
    );
  } else {
    await burst('64 logins, unlimited', 64, () => hasher.hash('pw'));
  }
}

Output of dart run bin/limit.dart and dart run bin/limit.dart limited:

logical processors: 24
64 logins, unlimited: first done 1636 ms, last 1744 ms, peak RSS 1613 MiB
logical processors: 24
64 logins, 12 at a time: first done 251 ms, last 1953 ms, peak RSS 531 MiB

Without a limit, all 64 hashes compete for the CPU. Nobody gets an answer for 1.6 seconds, and memory peaks at 1.6 GiB. With a limit, the first users are served in a quarter of a second, total throughput stays about the same, and memory stays bounded at roughly limit × m plus isolate overhead. Size the limit from the memory you can spare for hashing and the number of cores. Once the queue gets long, reject requests with HTTP 503 or 429 instead of letting it grow without bound. package:pool provides the same idea as a ready-made class.

A concurrency limit protects the server. It doesn't stop password guessing. Rate-limit login attempts per account and per IP address as well, as shown in Authentication.

Testing

Production parameters make a test suite slow. Use tiny ones in tests, and keep at least one hash made by another implementation as a known answer:

import 'package:test/test.dart';

import '../bin/hasher.dart';

void main() {
  // Tiny parameters: tests need correctness, not resistance to cracking.
  final hasher = PasswordHasher(memoryKiB: 64, iterations: 1);

  test('round trip', () async {
    final h = await hasher.hash('pw');
    expect(await hasher.verify('pw', h), isTrue);
    expect(await hasher.verify('pW', h), isFalse);
  });

  test('salt makes every hash different', () async {
    expect(await hasher.hash('pw'), isNot(await hasher.hash('pw')));
  });

  test('matches the reference C implementation', () async {
    // Computed with the reference C implementation (argon2-cffi).
    const h =
        r'$argon2id$v=19$m=65536,t=3,p=4$vDOb2YDX8ji8qCPyY7GA2Q'
        r'$CydfQxcvVm6APzd4JL7BZoGx6B53Wz1FeQN+4FQUejQ';
    expect(await hasher.verify('correct horse battery staple', h), isTrue);
  });

  test('test hashes are flagged for rehash by production settings', () async {
    expect(PasswordHasher().needsRehash(await hasher.hash('pw')), isTrue);
  });
}

Output of dart test/hasher_test.dart (or dart test):

+4: All tests passed!

The last test also guards the rehash logic: production settings must never accept a hash made with test parameters as up to date.

Checklist

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents