From 2130f4970f3540c122a7de63f9f9c5fb2370b62b Mon Sep 17 00:00:00 2001 From: Martin Dickopp Date: Tue, 12 Jan 2021 18:37:33 +0100 Subject: [PATCH] Improve password generation Generating an 8-bit random number and reducing it modulo 56 (characters.length) does not choose all numbers 0 to 55 with equal probability, but chooses 0 to 31 with higher probability than 32 to 55. This change improves the password generation algorithms by choosing all characters with equal probability. --- .../users/user-repository.service.ts | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/client/src/app/core/repositories/users/user-repository.service.ts b/client/src/app/core/repositories/users/user-repository.service.ts index 5189f00e3..e482a9edf 100644 --- a/client/src/app/core/repositories/users/user-repository.service.ts +++ b/client/src/app/core/repositories/users/user-repository.service.ts @@ -181,11 +181,21 @@ export class UserRepositoryService extends BaseRepository charactersLengthPower2) { + charactersLengthPower2 *= 2; + } + while (pw.length < length) { + const random = new Uint8Array(length - pw.length); + window.crypto.getRandomValues(random); + for (let i = 0; i < random.length; i++) { + const r = random[i] % charactersLengthPower2; + if (r < characters.length) { + pw += characters.charAt(r); + } + } } return pw; }