uuid-core
Version:
A simple UUID generator library for Node.js, NestJS, and Next.js
26 lines (20 loc) • 729 B
text/typescript
import { createHash } from "crypto";
import type { UUID, Namespace } from "./types";
export function v5(name: string, namespace: Namespace): UUID {
const nsBytes = Buffer.from(namespace.replace(/-/g, ""), "hex");
const nameBytes = Buffer.from(name);
const input = Buffer.concat([nsBytes, nameBytes]);
const hash = createHash("sha1").update(input).digest();
const output = Buffer.alloc(16);
hash.copy(output, 0, 0, 16);
output[6] = (output[6] & 0x0f) | 0x50;
output[8] = (output[8] & 0x3f) | 0x80;
const hex = output.toString("hex");
return [
hex.slice(0, 8),
hex.slice(8, 12),
hex.slice(12, 16),
hex.slice(16, 20),
hex.slice(20, 32),
].join("-") as UUID;
}