From HMAC to a 6-digit code

HOTP and TOTP turn a 20-byte HMAC-SHA-1 value into a short code with dynamic truncation: the hash itself chooses where to read.

What to build

Apply RFC 4226's dynamic truncation to HMAC values and print the codes.

Requirements

  • Each line is a 40-digit hex HMAC and the number of digits D.
  • offset = (last byte) & 0x0f.
  • Read 4 bytes from the offset, clear the top bit of the first (& 0x7f), and join them into one 31-bit number.
  • The code is that number mod 10^D, padded with leading zeros to D digits.

Input

One line per HMAC: the hex value and D.

Output

One code per line.

Constraints

D is 6, 7 or 8.

Example

Input:

1f8698690e02ca16618550ef7f19da8e945b555a 6

Output:

872921

Why it works

Using the low 4 bits of the last byte as the offset makes the read position depend on the hash, and masking the top bit avoids signed-number differences between languages.

Examples

Example 1 · Input
1f8698690e02ca16618550ef7f19da8e945b555a 6
Expected output
872921
Example 2 · Input
1f8698690e02ca16618550ef7f19da8e945b555a 8
Expected output
57872921

Hints

Hint 1

Turn the hex into an array of 20 numbers first.

Hint 2

Combine with (b0 & 0x7f) * 2**24 + b1 * 2**16 + b2 * 2**8 + b3 to stay in safe whole numbers.

Solution

Show one correct solution (try it yourself first)
let line = prompt();
while (line !== null) {
  const [hex, d] = line.trim().split(/\s+/);
  const bytes = [];
  for (let k = 0; k < hex.length; k += 2) bytes.push(parseInt(hex.slice(k, k + 2), 16));
  const o = bytes[19] & 0x0f;
  const number = (bytes[o] & 0x7f) * 2 ** 24 + bytes[o + 1] * 2 ** 16 + bytes[o + 2] * 2 ** 8 + bytes[o + 3];
  const digits = Number(d);
  console.log(String(number % 10 ** digits).padStart(digits, "0"));
  line = prompt();
}

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Two-factor authentication and one-time codes →