string-timing-safe-equal
Version:
crypto.timingSafeEqual, but works with strings
29 lines (28 loc) • 967 B
JavaScript
import * as crypto from "node:crypto";
import { Buffer } from "node:buffer";
export default function timingSafeEqual(a, b) {
let bytesA;
let bytesB;
if (typeof a === "string") {
if (typeof b !== "string") {
throw new TypeError("Both arguments must be of the same type");
}
// As an optimization, we can compare the string lengths before converting.
if (a.length !== b.length)
return false;
bytesA = Buffer.from(a, "utf16le");
bytesB = Buffer.from(b, "utf16le");
}
else if (a instanceof Uint8Array) {
if (!(b instanceof Uint8Array)) {
throw new TypeError("Both arguments must be of the same type");
}
bytesA = a;
bytesB = b;
}
else {
throw new TypeError("Both arguments must be strings or Uint8Arrays");
}
return (bytesA.byteLength === bytesB.byteLength &&
crypto.timingSafeEqual(bytesA, bytesB));
}