Generates, hashes, and validates single-use 2FA recovery (backup) codes.
By default, generates 10 codes formatted as XXXX-XXXX using Crockford
Base32 characters (0-9, A-Z excluding I, L, O, U) for high
readability and 40 bits of entropy per code.
Summary
Functions
Generates a list of unique recovery codes.
Hashes a recovery code using SHA-256 after normalization so that codes can be safely persisted in a database without storing plaintext values.
Hashes a list of recovery codes with hash/1.
Normalizes a recovery code by removing whitespace, hyphens, and underscores, and converting to uppercase.
Validates a user-submitted recovery code against a list of stored codes
(either plaintext or hashed via hash/1).
Types
@type option() :: {:count, pos_integer()} | {:groups, pos_integer()} | {:group_length, pos_integer()} | {:separator, binary()} | {:alphabet, binary()}
@type validate_option() :: {:hashed, :auto | boolean()}
Functions
Generates a list of unique recovery codes.
Options
:count- number of recovery codes to generate (default:10):groups- number of character groups per code (default:2):group_length- characters per group (default:4):separator- separator between groups (default:"-"):alphabet- ASCII character set to draw from (default: Crockford Base32)
Examples
codes = Ex2FA.RecoveryCodes.generate()
#=> ["7K9M-2XPQ", "B4N8-W3RT", ...]
Hashes a recovery code using SHA-256 after normalization so that codes can be safely persisted in a database without storing plaintext values.
Hashes a list of recovery codes with hash/1.
Normalizes a recovery code by removing whitespace, hyphens, and underscores, and converting to uppercase.
@spec validate(binary(), [binary()], [validate_option()]) :: {:ok, [binary()]} | {:error, :invalid_code}
Validates a user-submitted recovery code against a list of stored codes
(either plaintext or hashed via hash/1).
Input normalization strips whitespace, hyphens, and underscores and ignores letter case. Comparisons use constant-time equality.
Returns {:ok, remaining_codes} with the matched code removed (enforcing
single-use semantics), or {:error, :invalid_code} if no match is found.
Options
:hashed-:auto(default, detects"sha256:"-prefixed entries),true, orfalse