Menu
CoddyTech

Comparing Key Bytes

Part of the Auth and Security section of Coddy's Node.js journey. Lesson 5 of 24.

Two different Buffer objects can hold the same bytes. Comparing them with === checks object identity, not matching byte contents. For secret keys, use timingSafeEqual. A byte-by-byte comparison that stops at the first mismatch can leak information through its timing. This function uses a constant-time byte comparison; the rest of the login code must avoid timing leaks too.

const same = token.length === savedToken.length
    && timingSafeEqual(token, savedToken);

The length check matters because timingSafeEqual throws for different lengths. The && expression skips the comparison when lengths differ. The starter decodes the supplied hex strings into Buffers for you. Focus on returning a boolean result. A full password login first derives the attempted key, then performs this comparison.

challenge icon

Challenge

Easy

This is a small practice project. Its setup is provided; edit only exercise.js.

Return {"same":true} when given and expected hold equal bytes, otherwise false. POST {"given":"abcd","expected":"abcd"} to /result returns true. Changing given to abce or ab returns false without throwing. Inputs are valid hex.

Use the imported timingSafeEqual result after checking the byte lengths. Comparing encoded strings or Buffer identities is not the secure operation being practised.

Try it yourself

import { timingSafeEqual } from 'node:crypto';
export function exercise(input) {
    const given = Buffer.from(input.given, 'hex');
    const expected = Buffer.from(input.expected, 'hex');
    return { same: given === expected };
}

All lessons in Auth and Security

Practice on your own: Express playground