Files
suaveplan/packages/security-stack/crypto/crypto-utils/src/constant-time/constant-time-equal/constant-time-equal.test.ts
2026-05-27 23:47:53 +01:00

57 lines
1.7 KiB
TypeScript

import { describe, expect, it } from "@suaveplan/testing/runner";
import { constantTimeEqual } from "./constant-time-equal.js";
describe("constantTimeEqual", () => {
it("returns true for identical buffers", { timeout: 5000 }, () => {
const a = new Uint8Array([1, 2, 3]);
const b = new Uint8Array([1, 2, 3]);
expect(constantTimeEqual(a, b)).toBe(true);
});
it("returns true for empty buffers", { timeout: 5000 }, () => {
expect(constantTimeEqual(new Uint8Array(), new Uint8Array())).toBe(
true
);
});
it("returns false when contents differ at end", { timeout: 5000 }, () => {
expect(
constantTimeEqual(
new Uint8Array([1, 2, 3]),
new Uint8Array([1, 2, 4])
)
).toBe(false);
});
it("returns false when contents differ at start", { timeout: 5000 }, () => {
expect(
constantTimeEqual(
new Uint8Array([0, 2, 3]),
new Uint8Array([1, 2, 3])
)
).toBe(false);
});
it("returns false when lengths differ", { timeout: 5000 }, () => {
expect(
constantTimeEqual(new Uint8Array([1, 2]), new Uint8Array([1, 2, 3]))
).toBe(false);
});
it("runs the full loop regardless of mismatch", { timeout: 5000 }, () => {
// Property check: result only depends on whether any byte differs.
const a = new Uint8Array(32);
const b = new Uint8Array(32);
a[0] = 1;
b[0] = 2;
a[31] = 3;
b[31] = 4;
expect(constantTimeEqual(a, b)).toBe(false);
a[0] = 0;
b[0] = 0;
a[31] = 0;
b[31] = 0;
expect(constantTimeEqual(a, b)).toBe(true);
});
});