Password hashing
suggest changeA 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:
- why fast hashes like SHA-256 fail, and what salts fix
- what Argon2id's memory, iterations and parallelism parameters do, and how to pick them by measuring
- a reusable
PasswordHasherwith strict PHC string parsing, rehash detection and Unicode normalization - checking hashes made in other languages (Python's argon2-cffi), and adding a pepper
- verifying old bcrypt, PBKDF2 and unsalted SHA-1 hashes and migrating them to Argon2id
- limiting concurrent hashes on a server, and testing
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
- Equal passwords give equal hashes. Alice and Carol are exposed together. An attacker hashes a word list once and looks up every user at the same time. A rainbow table is a precomputed version of this.
- SHA-256 is fast. This loop does over half a million guesses per second on one core in Dart, and GPU crackers do billions. Most human-chosen passwords fall within hours.
A password hash fixes both problems:
- A random salt, unique per password and stored next to the hash, makes equal passwords hash differently and makes precomputed tables useless. The attacker has to attack each user separately.
- A tunable work factor makes each guess expensive. Memory-hard functions such as Argon2id and scrypt also need a lot of RAM for each guess. That makes GPUs and custom chips much less effective.
| 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:
- memory (
m, in KiB): how much RAM one hash uses. More memory is the main defense against GPUs. - iterations (
t): how many passes are made over that memory. Raises time without raising memory. - parallelism (
p): the number of independent lanes. Lanes can be computed on separate cores, sop > 1lowers wall-clock time if the implementation uses threads.
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:
- Aim for roughly 100 to 500 ms per hash on your production servers. Use as much memory as you can afford, multiplied by the number of logins that may run at once (see Limiting concurrent hashes below).
- On the Dart VM,
package:cryptographyruns Argon2 in pure Dart. For comparison, the C reference implementation (through Python's argon2-cffi) took 32 ms form=19456,t=2,p=1and 228 ms form=65536,t=3,p=1on the same machine. Dart is roughly 4 to 8 times slower. Attackers use optimized native or GPU code, so with pure Dart you spend more server time for the same protection. It's still the right choice for most Dart servers. Just choose parameters by memory first, then check the time. - With
p=4the package splits the lanes across isolates, which halved the wall-clock time here. It doesn't reduce the total CPU work, so on a busy server parallelism improves latency, not throughput.
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:
- parses the PHC string with a regular expression and rejects absurd parameters, so a corrupted or imported row can't make the server allocate gigabytes
- uses the hash length from the stored string, so 16- or 64-byte hashes from other systems verify too
- has a
needsRehash()that means "weaker than now", comparing each parameter - normalizes the password to Unicode NFC and caps its length
- runs the hash in a separate isolate so the server's event loop isn't blocked (see Isolates)
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:
- The PHC string format is
$argon2id$v=19$m=<KiB>,t=<iterations>,p=<lanes>$<salt>$<hash>, with salt and hash in standard Base64 without=padding.v=19means Argon2 version 1.3. The parameters travel with the hash, so you can change settings at any time and old hashes still verify. - Salt: 16 random bytes from
Random.secure()are plenty. Never reuse or derive salts. - Comparison:
Macfrompackage:cryptographyimplements==in constant time. A plain byte-by-byte loop stops at the first difference, which in theory leaks how many leading bytes matched. needsRehash()and equivalent settings: moving fromm=19456,t=2tom=47104,t=1flags every old hash because its memory is lower, even though the strength is about the same. That costs one extra hash per user at their next login. Ap=4hash from another system isn't flagged, since parallelism doesn't change strength much.- Length cap: Argon2 first compresses the password with BLAKE2b, so long passwords are cheap to hash and nothing is truncated. The cap is there to stop someone from posting a 50 MB "password". 1024 characters is far above the 64 that NIST asks you to accept.
- Unknown users: when the username doesn't exist, verify against a dummy hash anyway, so the response time doesn't reveal which accounts exist. The Authentication article shows how.
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
- Argon2's secret input (
optionalSecret) is part of the algorithm itself. The first line matches the output of the C reference implementation for the same password, salt, secret and parameters, so it works with any library that exposes the secret (for example thesecretfield of libargon2'sargon2_context). Many high-level libraries don't expose it. - HMAC first works with any password hash, including bcrypt, and is the approach OWASP describes. Hash the 32-byte MAC itself if the algorithm accepts bytes. For bcrypt, Base64-encode it first: some bcrypt implementations stop at a zero byte.
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
- Rehash on login works for any format, but only for users who log in. Dormant accounts keep their weak hashes for years.
- Wrapping fixes that.
wrapAll()runs once, offline, and replaces each unsalted SHA-1 hash withargon2id(sha1(password)). The bare SHA-1 value is never stored again, so a leak now exposes only Argon2id hashes. At login the password goes through SHA-1 and then Argon2id. After a successful login the wrapped hash is replaced by a plain Argon2id hash. Thesha1+prefix records the layering. The same trick works for MD5 or for low-iteration PBKDF2. - Recognize each format by its prefix. Anything unrecognized fails closed.
- Don't keep old formats forever. After a deadline, force a password reset for accounts still on a legacy format and delete the old code paths.
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
- Use Argon2id with a 16-byte random salt per password. OWASP's
m=19456,t=2,p=1is a good minimum, and more memory is better. - Store the full PHC string, so parameters can change later. Rehash on a successful login when
needsRehash()says so. - Parse stored hashes strictly, and cap both the parameters and the password length.
- Normalize passwords to NFC before hashing, and accept any characters.
- Compare hashes in constant time, and hash outside the isolate that handles requests.
- Limit how many hashes run at once, and rate-limit login attempts.
- Wrap legacy unsalted hashes in Argon2id right away instead of waiting for users to log in.
- Consider a pepper stored outside the database, with a version so it can be rotated.
- Test with small parameters plus a known-answer hash from a reference implementation.