From 8828b25a8fd8a85a713d12f114d4837f55127455 Mon Sep 17 00:00:00 2001 From: Jonas Wagner Date: Fri, 13 May 2022 07:56:13 +0200 Subject: [PATCH] randomString: generate a securely random string. Also, support lengths > 12 in case that's ever needed. This is used in at least one case (creating device tokens for users) where it seems important that the output is unpredictable. --- common/util/random.ts | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/common/util/random.ts b/common/util/random.ts index 740379e5..a4b3d110 100644 --- a/common/util/random.ts +++ b/common/util/random.ts @@ -1,7 +1,11 @@ -export const randomString = (length = 12) => - Math.random() - .toString(16) - .substring(2, length + 2) +// Returns a cryptographically random hexadecimal string of length `length` +// (thus containing 4*`length` bits of entropy). +export const randomString = (length = 12) => { + const bytes = new Uint8Array(Math.ceil(length / 2)) + crypto.getRandomValues(bytes) + const hex = bytes.reduce((s, b) => s + ('0' + b.toString(16)).slice(-2), '') + return hex.substring(0, length) +} export function genHash(str: string) { // xmur3