Agent Wranglers

ACC-19Recommended

Give recovery codes with the first second factor

When someone turns on a second factor, give them 10 single-use recovery codes of at least 64 random bits each, and store only their hashes.

How to do it

Make each code from a secure random source, such as 13 characters of base32 for 65 bits. NIST SP 800-63B-4 section 4.2.1.1 sets the 64-bit minimum for saved recovery codes. Show the codes once, with buttons to copy, download and print. Hash each one like a password. On success, mark the code used and show one new code at once, as section 4.2.1.1 requires. A new set cancels the old one. Email a notice whenever a code is used or replaced.

Examples

JavaScript example

import { randomInt } from 'node:crypto';

const CROCKFORD_BASE32 = '0123456789abcdefghjkmnpqrstvwxyz';
const CODE_LENGTH = 13; // 13 characters of 5 bits each give 65 bits
const CODE_COUNT = 10;

export const newRecoveryCodes = () => Array.from({ length: CODE_COUNT }, () =>
  Array.from({ length: CODE_LENGTH }, () => CROCKFORD_BASE32[randomInt(CROCKFORD_BASE32.length)]).join(''));

Python example

import secrets

CROCKFORD_BASE32 = "0123456789abcdefghjkmnpqrstvwxyz"
CODE_LENGTH = 13  # 13 characters of 5 bits each give 65 bits
CODE_COUNT = 10

def new_recovery_codes() -> list[str]:
    return ["".join(secrets.choice(CROCKFORD_BASE32) for _ in range(CODE_LENGTH)) for _ in range(CODE_COUNT)]

How to check

Sign in with one recovery code, then try it again. The second use fails, a new code was shown after the first, and the notice email arrived. No code appears in plain text in the database.

Sources

For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/accounts/second-factors-and-recovery/recovery-codes">Agent Wranglers accounts and identity playbook</a>. In code you write, add a comment next to it with the same link.