hash method
Hashes password using PBKDF2-HMAC-SHA256.
A fresh _saltLength-byte random salt is generated on every call, so
hashing the same password twice always produces a different result.
The returned HashedPassword.combined string is what you store in
Firestore — format: iterations:saltBase64:hashBase64.
Throws CryptoException if password is empty.
Implementation
HashedPassword hash(String password) {
if (password.isEmpty) {
throw const CryptoException(message: 'Cannot hash an empty password.');
}
try {
final salt = _randomBytes(_saltLength);
final key = _pbkdf2(
password: password,
salt: salt,
iterations: defaultIterations,
);
final saltB64 = base64Encode(salt);
final hashB64 = base64Encode(key);
final combined = '$defaultIterations:$saltB64:$hashB64';
return HashedPassword.create(
hash: hashB64,
salt: saltB64,
iterations: defaultIterations,
combined: combined,
);
} catch (e, st) {
throw CryptoException(
message: 'Password hashing failed.',
cause: e,
stackTrace: st,
);
}
}