File size: 922 Bytes
e81f4e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
export function randomBytes(length: number): Uint8Array {
	const bytes = new Uint8Array(length);
	crypto.getRandomValues(bytes);
	return bytes;
}

export function bytesToHex(bytes: Uint8Array): string {
	const nativeToHex = (bytes as Uint8Array & { toHex?: () => string }).toHex;
	if (typeof nativeToHex === "function") return nativeToHex.call(bytes);
	return Array.from(bytes)
		.map((byte) => byte.toString(16).padStart(2, "0"))
		.join("");
}

export function randHex(length: number): string {
	return bytesToHex(randomBytes(Math.ceil(length / 2))).slice(0, length);
}

export function uuid(): string {
	return crypto.randomUUID();
}

export function timingSafeStringEqual(a: string, b: string): boolean {
	const max = Math.max(a.length, b.length);
	let diff = a.length ^ b.length;
	for (let index = 0; index < max; index++) {
		diff |= (a.charCodeAt(index) || 0) ^ (b.charCodeAt(index) || 0);
	}
	return diff === 0;
}