108 words
1 minute
Constant-time comparison of strings in Node
Anubhav Gain
2024-08-06

Constant-time comparison of strings in Node#

When comparing secrets, passwords etc it’s important to use a constant-time compare function to avoid timing attacks.

In Python I use secrets.compare_digest(a, b), documented here.

I needed an equivalent in Node.js today. It has a crypto.timingSafeEqual() function but it’s a little tricky to use: it requires arguments that are Buffer, TypedArray or DataView and it throws an exception if they are not the same length.

I figured out this wrapper function so I can operate against strings of varying length:

const { timingSafeEqual } = require('crypto');
const compare = (a, b) => {
try {
return timingSafeEqual(Buffer.from(a, "utf8"), Buffer.from(b, "utf8"));
} catch {
return false;
}
};
Constant-time comparison of strings in Node
https://mranv.pages.dev/posts/constant-time-comparison-of-strings-in-node/
Author
Anubhav Gain
Published at
2024-08-06
License
CC BY-NC-SA 4.0