timingSafeEqual
import { timingSafeEqual } from "jsr:@ende/crypto";function
function timingSafeEqual(a: ArrayBufferView | ArrayBufferLike, b: ArrayBufferView | ArrayBufferLike): booleanWhen checking the values of cryptographic hashes are equal, default comparisons can be susceptible to timing based attacks, where attacker is able to find out information about the host system by repeatedly checking response times to equality comparisons of values.
It is likely some form of timing safe equality will make its way to the
WebCrypto standard (see:
w3c/webcrypto#270), but until
that time, timingSafeEqual() is provided.
Note: This is a best-effort constant-time comparison implemented in
JavaScript. The V8 JIT compiler does not provide formal constant-time
guarantees, and inputs backed by SharedArrayBuffer are susceptible to
concurrent modification during comparison.
a: ArrayBufferView | ArrayBufferLikeThe first value to compare.
b: ArrayBufferView | ArrayBufferLikeThe second value to compare.
Returns
true if the values are equal, otherwise false.
Example: Usage
import { timingSafeEqual } from "@ende/crypto/timing-safe-equal";
import { assert } from "@ende/assert";
const a = await crypto.subtle.digest(
"SHA-384",
new TextEncoder().encode("hello world"),
);
const b = await crypto.subtle.digest(
"SHA-384",
new TextEncoder().encode("hello world"),
);
assert(timingSafeEqual(a, b));