Skip to content

Commit 6ad317e

Browse files
committed
Fix sign bit
1 parent 9a1f85b commit 6ad317e

File tree

2 files changed

+10
-8
lines changed

2 files changed

+10
-8
lines changed

cryptorand/numbers.go

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,26 +10,28 @@ type cryptoSource struct {
1010
err error
1111
}
1212

13-
func (*cryptoSource) Seed(seed int64) {
13+
func (*cryptoSource) Seed(_ int64) {
1414
// Intentionally disregard seed
1515
}
1616

1717
func (c *cryptoSource) Int63() int64 {
18-
var seed int64
19-
err := binary.Read(rand.Reader, binary.BigEndian, &seed)
18+
var n int64
19+
err := binary.Read(rand.Reader, binary.BigEndian, &n)
2020
if err != nil {
2121
c.err = err
2222
}
23-
return 0
23+
// The sign bit must be cleared to ensure the final value is non-negative.
24+
n &= 0x7fffffffffffffff
25+
return n
2426
}
2527

2628
func (c *cryptoSource) Uint64() uint64 {
27-
var seed uint64
28-
err := binary.Read(rand.Reader, binary.BigEndian, &seed)
29+
var n uint64
30+
err := binary.Read(rand.Reader, binary.BigEndian, &n)
2931
if err != nil {
3032
c.err = err
3133
}
32-
return 0
34+
return n
3335
}
3436

3537
// secureRand returns a cryptographically secure random number generator.

cryptorand/numbers_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ func TestIntn(t *testing.T) {
2626
v, err := cryptorand.Intn(100)
2727
require.NoError(t, err, "unexpected error from Intn")
2828
t.Logf("value: %v <- random?", v)
29-
require.True(t, v >= 0, "values must be positive")
29+
require.GreaterOrEqual(t, v, 0, "values must be positive")
3030
require.True(t, v < 100, "values must be less than 100")
3131
}
3232

0 commit comments

Comments
 (0)