sc-site-sync/lib/common/hash.js
2026-10-19 01:25:16 -05:00

28 lines
826 B
JavaScript

// Content hashing and constant-time comparison.
const crypto = require("crypto");
// SHA-256 of a Buffer or string (utf8) as lowercase hex; null/undefined hash as "".
const sha256Hex = (data) => {
const buf = Buffer.isBuffer(data) ? data : Buffer.from(data || "");
return crypto.createHash("sha256").update(buf).digest("hex");
};
// Timing-safe equality of two Buffers or strings (utf8): the comparison time
// does not depend on where they first differ (only on the length).
const constantTimeEqual = (a, b) => {
const ba = Buffer.isBuffer(a) ? a : Buffer.from(String(a));
const bb = Buffer.isBuffer(b) ? b : Buffer.from(String(b));
if (ba.length !== bb.length) {
return false;
}
return crypto.timingSafeEqual(ba, bb);
};
module.exports = {
sha256Hex,
constantTimeEqual
};