nish/crypto/bcrypt

Bcrypt password hashing, $2b$ out and $2a$, $2b$, $2y$ in. It makes the hash libxcrypt's crypt_r and crypt_blowfish make, and verifies as they do but for $2x$ and a digest character outside the alphabet. Where OpenBSD's bcrypt.c and Go's x/crypto answer otherwise is the interoperability table in docs/security/crypto-bcrypt.md.

import {
  BCRYPT_HASH_LENGTH,
  BCRYPT_MAX_COST,
  BCRYPT_MAX_PASSWORD,
  BCRYPT_MIN_COST,
  BCRYPT_SALT_SIZE,
  bcryptCalibrate,
  bcryptHash,
  bcryptHash4,
  bcryptHashN,
  bcryptVerify,
  bcryptVerify4,
  bcryptVerifyN,
} from "nish/crypto/bcrypt";
import { bcryptHash, bcryptVerify } from "nish/crypto/bcrypt"
import { Secret, secret } from "nish:secret"

const pw: Secret<u8[]> = secret(passwordBytes)
const hash: Result<string, string> = bcryptHash(pw, randomBytes(16), 12)
// "$2b$12$" + 22 salt characters + 31 digest characters
const ok: Result<boolean, string> = bcryptVerify(pw, storedHash)
Several at once

bcryptHashN and bcryptVerifyN take one to six passwords (lane 0 always, a null lane skipped) and run their Blowfish encryptions interleaved in one loop, so one core does the work of several hashes in well under the time of as many; each result is the single path's, byte for byte. bcryptVerifyN groups lanes by the cost their hash names, and a malformed hash in any lane is an Err for the whole call, naming the lane, before anything is hashed. bcryptHash4 and bcryptVerify4 are the same for up to four.

Which width is fastest depends on the core (how many loads it issues a cycle, how much L1 the states fill), so bcryptCalibrate measures it: it times widths one to six at cost 4 on throwaway passwords and answers the one with the least time per hash. Call it once, at startup.

The password is a `Secret`

The password is a Secret<u8[]> (nish:secret). The key schedule and the 2^cost rounds run inside exposeWith; the Blowfish state (the P-array and the four S-boxes, 1042 words), the expanded key and the key-stream copy are wiped before it returns. bcryptVerify rebuilds the whole 60-character hash and compares it with timingSafeEqual inside the same exposeWith, then wipes the rebuilt hash and the given hash's bytes; the batch wipes its state and digests and, in bcryptVerifyN, each lane's rebuilt and given hash. The hash strings bcryptHash and bcryptHashN return are public and are not wiped, nor are the bytes they are made from.

The key is the reference's

The bytes up to the first NUL, then one NUL, repeated until 72 bytes are taken: a password longer than 72 bytes hashes as its first 72, and bytes after an embedded NUL are not read, as under crypt_r; docs/security/crypto-bcrypt.md says why a longer password is cut rather than refused. Bytes above 127 are unsigned, as $2b$ and $2y$ define them.

A $2a$ hash gets crypt_blowfish's countermeasure for the old sign-extension bug: when an 8-bit byte was sign-extended into a key word and yet the buggy and the correct key came out equal, one bit of the first P word is flipped, as crypt_blowfish flips it, so the $2a$ digest of such a password (\xff\xff\xa3) is not its $2y$ one. It takes an 8-bit byte after the first byte of a key word with only 0xff bytes before it, every such byte in all 18 words being so placed, which UTF-8 never holds. $2x$ (the bug itself) is refused.

Errors are `Err`s

A salt that is not 16 bytes, a cost outside 4–31, or a hash string that is not one (the wrong length, an unknown prefix, a cost that is not two digits in range, a character outside the alphabet) is an Err naming it. A well-formed hash that is not this password's is Ok(false), and so is one whose last salt character has bits set the reference drops, since the hash the reference makes from it differs.

The cost comes from the hash

bcryptVerify runs 2^cost rounds for the cost the hash names, so a $2b$31$ hash someone hands you takes 2^31 rounds, hours of one core. Verify only hashes you stored.

Pure

No I/O and no C, so it builds for wasm32; bcryptCalibrate alone reads the monotonic clock (clock in --emit-capabilities), and the hashes never do. A std/threads task may call bcryptHash, bcryptVerify and the batch: everything they wipe is an array they made, never the caller's hashes, and the batch's state is a Secret of a fresh array (docs/security/crypto-bcrypt.md). A cost-12 hash takes a few hundred milliseconds of one core; a server runs it off its event loop, on a task (docs/guide/using-nish/password-hashing.md).

The algorithm is Provos and Mazières's ("A Future-Adaptable Password Scheme", USENIX 1999). The code is adapted from Solar Designer's crypt_blowfish 1.3, which carries the notice below, and the 1042 initial words, the hexadecimal digits of π, are its BF_init_state. Closest upstream for each part: bcryptInitState is BF_init_state; bcryptEncrypt and the rounds in bcryptBody are BF_ENCRYPT/BF_ROUND; bcryptBody is BF_body; bcryptSetKey is BF_set_key; bcryptDecodeSalt and bcryptEncode are BF_decode and BF_encode; bcryptExposed is the part of BF_crypt after the setting is parsed, and bcryptParse that parse.

The state is one flat u32[] with P first (words 0–17) and the S-boxes after (18–1041), so the body walks it in one pass, and every S-box index is an i32 masked to 0–255, which the checker proves in bounds (BCRYPT_STATE_WORDS). The magic-string encryption, the parsing and the alphabet are separate functions so a several-lane kernel can share them.

Names carry the bcrypt prefix because a std/ module's private functions share the importing program's flat symbol namespace (docs/wp26-stdlib.md §3e).

Adapted from crypt_blowfish (https://www.openwall.com/crypt/), crypt_blowfish.c. Written by Solar Designer, 1998-2014, and placed in the public domain, with a permissive licence as the fallback; see std/crypto/LICENSE-crypt_blowfish.

crypt_blowfish's notice, kept as it asks:

Written by Solar Designer <solar at openwall.com> in 1998-2014. No copyright is claimed, and the software is hereby placed in the public domain. In case this attempt to disclaim copyright and place the software in the public domain is deemed null and void, then the software is Copyright (c) 1998-2014 Solar Designer and it is hereby released to the general public under the following terms:

Redistribution and use in source and binary forms, with or without modification, are permitted.

There's ABSOLUTELY NO WARRANTY, express or implied.

It is my intent that you should be able to use this on your system, as part of a software package, or anywhere else to improve security, ensure compatibility, or for any other purpose. I would appreciate it if you give credit where it is due and keep your modifications in the public domain as well, but I don't require that in order to let you place this code and any modifications you make under a license of your choice.

This implementation is fully compatible with OpenBSD's bcrypt.c for prefix "$2b$", originally by Niels Provos <provos at citi.umich.edu>, and it uses some of his ideas. The password hashing algorithm was designed by David Mazieres <dm at lcs.mit.edu>.

Functions

bcryptCalibrate

The batch width, 1 to 6, that hashes fastest per password on this core: each width timed on throwaway passwords at cost 4, the least time of a few runs divided by the width. It measures rather than guesses, since the best width turns on the core's load ports, its registers and what else is running, and it keeps nothing between calls, so call it once, at startup, and keep the answer. A few tens of milliseconds of one core.

const bcryptCalibrate: () => i32
returnsi32

How many passwords, 1 to 6, to give each batch call.

bcryptHash

The $2b$ hash of password with a 16-byte salt and 2^cost rounds: 60 characters, $2b$, the two-digit cost, $, the salt and the digest in bcrypt's base64. The salt must come from a CSPRNG and be fresh for each hash. An Err for a salt of another length or a cost outside 4–31.

const bcryptHash: (
  password: Secret<u8[]>,
  salt: u8[],
  cost: i32,
) => Result<string, string>
passwordSecret<u8[]>required

The password, read only inside exposeWith; the caller still owns and wipes it.

saltu8[]required

16 fresh random bytes.

costi32required

The log2 of the round count, 4 to 31.

returnsResult<string, string>

The 60-character hash, which is public, or an Err naming the bad salt or cost.

bcryptHash4

bcryptHashN for up to four passwords, salts 64 bytes: the same hashes, four strings. An Err for salts of another length than 64 or a cost outside 4–31.

const bcryptHash4: (
  p0: Secret<u8[]>,
  p1: Secret<u8[]> | null,
  p2: Secret<u8[]> | null,
  p3: Secret<u8[]> | null,
  salts: u8[],
  cost: i32,
) => Result<string[], string>
p0Secret<u8[]>required

Lane 0's password, always hashed; read only inside exposeWith, and the caller still owns and wipes it.

p1Secret<u8[]> | nullrequired

Lane 1's password, or null to skip the lane.

p2Secret<u8[]> | nullrequired

Lane 2's password, or null to skip the lane.

p3Secret<u8[]> | nullrequired

Lane 3's password, or null to skip the lane.

saltsu8[]required

64 fresh random bytes, lane k's salt at 16k.

costi32required

The log2 of the round count, 4 to 31.

returnsResult<string[], string>

Four hash strings, "" for a lane not given, or an Err for bad salts or cost.

bcryptHashN

The $2b$ hashes of up to six passwords at once, each as bcryptHash makes it: lane k with the 16 bytes of salts at 16k and 2^cost rounds. Lane 0 is always hashed; a null lane gives "" and its salt bytes are not read. The w lanes given run as one computation on one thread with their cost rounds interleaved, whatever positions they are in; one lane runs as bcryptHash. Which w is fastest per hash depends on the core (bcryptCalibrate measures it). An Err for salts of another length than 96 or a cost outside 4–31.

const bcryptHashN: (
  p0: Secret<u8[]>,
  p1: Secret<u8[]> | null,
  p2: Secret<u8[]> | null,
  p3: Secret<u8[]> | null,
  p4: Secret<u8[]> | null,
  p5: Secret<u8[]> | null,
  salts: u8[],
  cost: i32,
) => Result<string[], string>
p0Secret<u8[]>required

Lane 0's password, always hashed; read only inside exposeWith, and the caller still owns and wipes it.

p1Secret<u8[]> | nullrequired

Lane 1's password, or null to skip the lane.

p2Secret<u8[]> | nullrequired

Lane 2's password, or null to skip the lane.

p3Secret<u8[]> | nullrequired

Lane 3's password, or null to skip the lane.

p4Secret<u8[]> | nullrequired

Lane 4's password, or null to skip the lane.

p5Secret<u8[]> | nullrequired

Lane 5's password, or null to skip the lane.

saltsu8[]required

96 fresh random bytes, lane k's salt at 16k.

costi32required

The log2 of the round count, 4 to 31.

returnsResult<string[], string>

Six hash strings, "" for a lane not given, or an Err for bad salts or cost.

bcryptVerify

Whether hash is password's: Ok(true) or Ok(false), decided by a constant-time compare of all 60 characters with the hash rebuilt from the password and hash's own prefix, salt and cost. $2a$, $2b$ and $2y$ are read; an Err names what makes hash not a bcrypt hash.

const bcryptVerify: (
  password: Secret<u8[]>,
  hash: string,
) => Result<boolean, string>
passwordSecret<u8[]>required

The password, read only inside exposeWith; the caller still owns and wipes it.

hashstringrequired

A stored hash; its cost sets the work, so it must be one you stored.

returnsResult<boolean, string>

Ok(true) only for this password's hash, Ok(false) for another's, or an Err for a malformed hash.

bcryptVerify4

bcryptVerifyN for up to four passwords and four hashes: the same answers, four of them, and the same lane errors.

const bcryptVerify4: (
  p0: Secret<u8[]>,
  p1: Secret<u8[]> | null,
  p2: Secret<u8[]> | null,
  p3: Secret<u8[]> | null,
  hashes: string[],
) => Result<boolean[], string>
p0Secret<u8[]>required

Lane 0's password, always hashed; read only inside exposeWith, and the caller still owns and wipes it.

p1Secret<u8[]> | nullrequired

Lane 1's password, or null to skip the lane.

p2Secret<u8[]> | nullrequired

Lane 2's password, or null to skip the lane.

p3Secret<u8[]> | nullrequired

Lane 3's password, or null to skip the lane.

hashesstring[]required

Four strings, lane k's stored hash at k; a skipped lane's is not read.

returnsResult<boolean[], string>

Four answers, false for a skipped lane, or an Err naming a malformed lane or a count that is not four.

bcryptVerifyN

Whether each of hashes (six strings) is its lane's password's, as bcryptVerify decides it: lane 0 always, a null lane false and its string not read. Lanes are grouped by the cost their hash names and each group of two or more runs as one interleaved computation; a group of one runs as bcryptVerify. A malformed hash in any given lane makes the whole call an Err naming the lane ("bcrypt: lane 2: …") before any hashing, so one bad row in a batch cannot be read as a wrong password.

const bcryptVerifyN: (
  p0: Secret<u8[]>,
  p1: Secret<u8[]> | null,
  p2: Secret<u8[]> | null,
  p3: Secret<u8[]> | null,
  p4: Secret<u8[]> | null,
  p5: Secret<u8[]> | null,
  hashes: string[],
) => Result<boolean[], string>
p0Secret<u8[]>required

Lane 0's password, always hashed; read only inside exposeWith, and the caller still owns and wipes it.

p1Secret<u8[]> | nullrequired

Lane 1's password, or null to skip the lane.

p2Secret<u8[]> | nullrequired

Lane 2's password, or null to skip the lane.

p3Secret<u8[]> | nullrequired

Lane 3's password, or null to skip the lane.

p4Secret<u8[]> | nullrequired

Lane 4's password, or null to skip the lane.

p5Secret<u8[]> | nullrequired

Lane 5's password, or null to skip the lane.

hashesstring[]required

Six strings, lane k's stored hash at k; a skipped lane's is not read.

returnsResult<boolean[], string>

Six answers, false for a skipped lane, or an Err naming a malformed lane or a count that is not six.

Limits

31

BCRYPT_MAX_COST: i32

The largest cost: 2^31 rounds.

4

BCRYPT_MIN_COST: i32

The smallest cost the reference accepts: 2^4 rounds.

Constants

60

BCRYPT_HASH_LENGTH: i32

The length of a bcrypt hash string: $2b$, two cost digits, $, 22 salt and 31 digest characters.

72

BCRYPT_MAX_PASSWORD: i32

The number of password bytes the key schedule reads; the rest are not.

16

BCRYPT_SALT_SIZE: i32

The length in bytes of a bcrypt salt.