Skip to content

Commit f13967a

Browse files
committed
Use modulo arithmetic instead
also I think this was just wrong in that it was subtracting 1 unnercessarily because we already used < rather than <= below.
1 parent 1f1d6f0 commit f13967a

File tree

1 file changed

+3
-2
lines changed

1 file changed

+3
-2
lines changed

src/randomstring.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,8 @@ export function secureRandomStringFrom(len: number, chars: string): string {
7474
// this as we can't possibly map them onto the character set while keeping each character equally
7575
// likely to be chosen (minus 1 to convert to indices in a string). (Essentially, we're using a d8
7676
// to choose between 7 possibilities and re-rolling on an 8, keeping all 7 outcomes equally likely.)
77-
const maxRandValue = Math.floor(255 / chars.length) * chars.length - 1;
77+
// Our random values must be strictly less than this
78+
const randomValueCutoff = 256 - (256 % chars.length);
7879

7980
// Grab 30% more entropy than we need. This should be enough that we can discard the values that are
8081
// too high without having to go back and grab more unless we're super unlucky.
@@ -92,7 +93,7 @@ export function secureRandomStringFrom(len: number, chars: string): string {
9293

9394
const randomByte = entropyBuffer[entropyBufferPos++];
9495

95-
if (randomByte < maxRandValue) {
96+
if (randomByte < randomValueCutoff) {
9697
result.push(chars[randomByte % chars.length]);
9798
}
9899
}

0 commit comments

Comments
 (0)