Hashing passwords with Argon2 and bcrypt
Server-side JavaScript can hash passwords with Argon2 or bcrypt through crypto.subtle. Use them to store a password safely and to check a password someone types against the stored hash.
The two are not equally standard:
- Argon2 follows a draft web standard, 'Modern Algorithms in the Web Cryptography API'. The draft may still change, and if it does, Pagelove will follow it.
- bcrypt is a Pagelove extension. It is not part of any web standard, so the same code will not run in a browser.
Sessel has the same algorithms as "password".argon2() and "password".bcrypt(), and the two languages share one implementation. JavaScript can check a hash Sessel made: verify checks a Sessel bcrypt string, and Argon2id with the salt and settings from a Sessel Argon2 string gives the same hash. Sessel cannot check hashes, because it has no verify method and its argon2() always picks a new salt. The limits are the same where the options are the same. Sessel always uses one lane and gives 4 to 64 bytes of output, while JavaScript allows more lanes and up to 64 KiB of output.
When to use
Use Argon2id for new work. It is the current recommendation for password storage. Use bcrypt when you need to check hashes made by another system, or made by Sessel's bcrypt().
Do not use a plain digest such as SHA-256 for passwords. It is fast, which makes guessing easy.
Argon2
Syntax
const key = await crypto.subtle.importKey(
"raw-secret", new TextEncoder().encode(password), "Argon2id", false, ["deriveBits"]);
const bits = await crypto.subtle.deriveBits(
{ name: "Argon2id", nonce, parallelism: 1, memory: 19456, passes: 2 }, key, 256);
The algorithm names are Argon2id, Argon2i and Argon2d, matched without regard to case. The key must be imported in the raw-secret format, must not be extractable, and may have only the deriveBits and deriveKey usages. deriveKey takes the same parameters and makes an AES or HMAC key from the password. An AES key must be 128, 192 or 256 bits, and the key's usages must suit it: for example encrypt and decrypt for AES-GCM, or sign and verify for HMAC. These rules apply to deriveKey with PBKDF2, HKDF and X25519 too.
An HMAC key derived without a length gets the hash's block size, as in browsers: 512 bits for SHA-1 and SHA-256, 1024 bits for SHA-384 and SHA-512. Before #1768 Pagelove gave it the hash's output length instead, for example 256 bits for SHA-256. If you stored something signed with a key derived that way, pass the old length, such as length: 256, so the key still matches.
| Parameter | Required | What it is |
|---|---|---|
nonce |
yes | The salt, as bytes. Use 16 random bytes for each password, and store them with the hash. At least 8 bytes |
parallelism |
yes | The number of lanes, 1 or more. Pagelove computes the lanes one after another, so more lanes add work without making it faster |
memory |
yes | Memory in KiB. At least 8 for each lane, and at most 262,144 (256 MiB) |
passes |
yes | The number of passes over the memory, 1 or more |
version |
no | Must be 19 if given, the only version there is |
secretValue |
no | A secret key (a "pepper") mixed into the hash, as bytes |
associatedData |
no | Extra data mixed into the hash, as bytes. At most 32 bytes |
The length you pass to deriveBits is in bits. It must be a multiple of 8 and at least 32. At most 524,288 bits (64 KiB).
The recommended settings for logins are memory: 19456, passes: 2, parallelism: 1 (19 MiB), from the OWASP password storage guidance, or memory: 65536, passes: 3, parallelism: 4 (64 MiB) from section 4 of RFC 9106. Pagelove computes the 4 lanes one after another, so the time depends on memory times passes, as with one lane.
Store and check a password
deriveBits gives the raw hash. Store it together with the nonce and the settings you used.
const enc = new TextEncoder();
async function argon2(password, nonce) {
const key = await crypto.subtle.importKey(
"raw-secret", enc.encode(password), "Argon2id", false, ["deriveBits"]);
return new Uint8Array(await crypto.subtle.deriveBits(
{ name: "Argon2id", nonce, parallelism: 1, memory: 19456, passes: 2 }, key, 256));
}
// When the password is set:
const nonce = crypto.getRandomValues(new Uint8Array(16));
const hash = await argon2(password, nonce);
// Store nonce and hash, for example as base64.
To check a password, hash it again with the stored nonce and settings, then compare the two hashes. Compare every byte rather than stopping at the first difference, so the time taken does not show how much matched:
function sameBytes(a, b) {
if (a.length !== b.length) return false;
let diff = 0;
for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];
return diff === 0;
}
const ok = sameBytes(await argon2(typed, storedNonce), storedHash);
bcrypt
bcrypt gives the standard $2b$ string, which carries its own cost and salt. Pagelove offers it in the same shape as Argon2.
Syntax
const key = await crypto.subtle.importKey(
"raw-secret", new TextEncoder().encode(password), "bcrypt", false, ["deriveBits", "verify"]);
// Make a hash:
const salt = crypto.getRandomValues(new Uint8Array(16));
const stored = new TextDecoder().decode(
await crypto.subtle.deriveBits({ name: "bcrypt", cost: 12, salt }, key));
// Check a password against a stored hash:
const ok = await crypto.subtle.verify(
"bcrypt", key, new TextEncoder().encode(stored), new Uint8Array(0));
The key must be imported in the raw-secret format, must not be extractable, and may have only the deriveBits and verify usages.
| Parameter | Required | What it is |
|---|---|---|
salt |
yes | 16 random bytes |
cost |
yes | From 4 to 31. Each step up doubles the time. 12 is a common choice |
deriveBits returns the 60 bytes of the $2b$ string. Leave out the length, or pass 480.
verify checks the password in the key against a stored $2a$, $2b$ or $2y$ string, passed as bytes in the signature argument. It refuses the legacy $2x$ form, which comes from an old bcrypt with a bug and cannot be checked correctly. It compares the hashes in constant time. The data argument must be empty, because the password comes from the key. verify resolves true or false.
bcrypt reads only the first 72 bytes of a password and ignores the rest. deriveKey is not available for bcrypt.
How long hashing takes
These algorithms are slow on purpose, and once hashing starts it cannot be stopped part-way. So before it starts, Pagelove estimates how long the work will take on the server and refuses work that will not finish in time. The time allowed is what is left of the request's time budget. When the request has none, the whole JavaScript call gets 5 seconds, and every hash in it shares them. Refused work rejects with OperationError, and the message says the work would exceed the time budget. Lower the cost, memory or passes.
The server also runs only as many Argon2 and bcrypt hashes at once as it has processor cores, and bcrypt verify counts as one. PBKDF2 and HKDF are not limited this way. One site may use at most half of those slots, and at least one. On a server with 2 or more slots, that stops one site taking them all. If your site is already using its share, the call is refused at once. Otherwise a hash waits for a free slot only while the time left still covers the hash. If no slot comes free in that time, or your site reaches its share while the hash waits, the call is refused. Either way the promise rejects with OperationError, and the message says the server, or your site, is already running as many hashes as it may and to try again shortly. Every busy refusal's message, including the one for Argon2 memory, ends with try again shortly, and no other refusal's message does, so a script that catches the error can tell a busy server apart by that ending. This refusal is about load on the server, not your settings. If your script catches the error, your script decides what happens next. If your script lets that same error escape, or throws the same object again, the request answers 503 Service Unavailable with a Retry-After: 1 header. If your script throws a different error instead, that error is your script's own. A Trigger or Processor gets the same answer: the client gets the Trigger's or Processor's own error document, with status 503 and a Retry-After: 1 header. The one exception is a Processor refusal after the request's save was stored. It is still 503, but it has no Retry-After header, because a retry would store the save again. Other errors in a Trigger or Processor still answer 500. A script run by a WebDAV auth-credentials-query that lets the error escape also gets 503 Service Unavailable with a Retry-After: 1 header. It does so whatever the site's auth-failure-mode is, and the sign-in is never let in.
On a modern server processor, bcrypt at cost 12 takes about a fifth of a second, Argon2id at 19 MiB and 2 passes about 20 milliseconds, and Argon2id at 64 MiB and 3 passes (with 1 lane or 4) under a tenth of a second. So the recommended settings fit well inside 5 seconds. Each step of bcrypt cost doubles the time: cost 16 takes about 16 times as long as cost 12. The estimate is made from short timings on the server, so work that only just fits may run a little over. PBKDF2 and HKDF have the same time check. For PBKDF2 it counts the password, the salt and the iterations; for HKDF, the key, the salt and info.
The bytes of PBKDF2's and HKDF's output, and of every key crypto.subtle makes, count against the request's memory budget, like Argon2's memory below. If they do not fit, the call rejects with OperationError and the budget stays used up. When the request has no memory budget, the keys and output of one JavaScript call may not pass 16 MiB in total instead.
PBKDF2 now reads its parameters as browsers do. iterations, salt and hash are required. iterations must be a number from 1 to 4,294,967,295; a fraction is cut to a whole number, and a string such as "600000" is read as that number. Before #1768, an iterations that was missing, null, negative, too large, not a number or behind a getter that threw ran a single iteration, and a missing salt was empty. If you stored a password hash made that way, it no longer matches. To check it, pass what was really used: iterations: 1, and salt: new Uint8Array(0) if you gave no salt. Then store the password again with proper settings. HKDF's salt and info are required in the same way.
Argon2's memory is also counted against the request's memory budget. If it does not fit, hashing does not start and the call rejects with OperationError. The memory budget then stays used up, so later work in the same request may fail too, even if you catch the error.
One server process runs at most 1 GiB of Argon2 memory at once, for all requests together, and each site at most half of that (512 MiB). A call that would go past either limit rejects with OperationError and can be tried again. It is the same busy refusal, so an error that escapes your script answers 503 with Retry-After: 1.
Error cases
The methods return promises. When one fails, the promise rejects with a DOMException whose name says why. A TypeError in the table is a JavaScript TypeError, as in browsers, not a DOMException. When reading the algorithm's name, its hash where it has one, or one of the parameters on this page, runs a getter or valueOf that throws, the promise rejects with whatever it threw.
| What happened | name |
|---|---|
A format other than raw-secret |
NotSupportedError |
| An extractable key, a usage the algorithm does not allow, or no usages | SyntaxError |
A required parameter is missing, a number is negative, not a number, or too large for its type (over 255 for cost and version, over 4,294,967,295 for the others), or bytes are not a BufferSource, the key argument is not a key crypto.subtle made, a usage is not a WebCrypto key usage, or a derived AES length is over 65,535 |
TypeError |
| The key was made for another algorithm, or lacks the usage | InvalidAccessError |
A parameter is inside its type but outside the ranges above (for example a bcrypt cost of 32, or memory over 262,144), the length is wrong, the work would exceed the time or memory budget, no hashing slot was free for the site in time, the server's or the site's Argon2 memory is in use, a stored bcrypt string is malformed or $2x$, or verify data is not empty |
OperationError |
sign with bcrypt or Argon2, verify with Argon2, or deriveKey with bcrypt |
NotSupportedError |