Newsletter
TechAnV Blog
Get updates on security engineering, Rust, eBPF, and DevSecOps. No spam, unsubscribe anytime.
Check your inbox and click the confirmation link to complete your subscription.
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:
1const { timingSafeEqual } = require('crypto');2
3const compare = (a, b) => {4 try {5 return timingSafeEqual(Buffer.from(a, "utf8"), Buffer.from(b, "utf8"));6 } catch {7 return false;8 }9};Newsletter
TechAnV Blog
Get updates on security engineering, Rust, eBPF, and DevSecOps. No spam, unsubscribe anytime.
Check your inbox and click the confirmation link to complete your subscription.