]> Cypherpunks repositories - gostls13.git/commit
crypto/rand: only read necessary bytes for Int
authorWade Simmons <wade@wades.im>
Tue, 23 May 2017 00:31:17 +0000 (20:31 -0400)
committerBrad Fitzpatrick <bradfitz@golang.org>
Tue, 23 May 2017 21:02:14 +0000 (21:02 +0000)
commit8a2553e380196dda556608e2fe79881004770eb9
tree37d896fad17b0d5e00322323ba5fd8ca37ee6b85
parent9f03e89552075d88184469fa7701007ed8b36130
crypto/rand: only read necessary bytes for Int

We only need to read the number of bytes required to store the value
"max - 1" to generate a random number in the range [0, max).

Before, there was an off-by-one error where an extra byte was read from
the io.Reader for inputs like "256" (right at the boundary for a byte).
There was a similar off-by-one error in the logic for clearing bits and
thus for any input that was a power of 2, there was a 50% chance the
read would continue to be retried as the mask failed to remove a bit.

Fixes #18165.

Change-Id: I548c1368990e23e365591e77980e9086fafb6518
Reviewed-on: https://go-review.googlesource.com/43891
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
Run-TryBot: Brad Fitzpatrick <bradfitz@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
src/crypto/rand/util.go
src/crypto/rand/util_test.go