Skip to content

Commit c18f398

Browse files
FiloSottilegopherbot
authored andcommitted
crypto/rand: make Prime not deterministic for a fixed input stream
rand.Prime does not guarantee the precise prime selection algorithm as part of its contract. For example, it changed slightly in CL 387554. We want to ensure that no tests come to rely on it staying the same, so just like other cryptographic functions that use randomness in an unspecified way (ECDSA signing, RSA PKCS #1 v1.5 encryption, RSA key generation), make it randomly read an extra byte or not. Change-Id: Ib9079c03360812d412b7c21d5a06caadabb4a8bf Reviewed-on: https://go-review.googlesource.com/c/go/+/391554 Run-TryBot: Filippo Valsorda <[email protected]> Auto-Submit: Filippo Valsorda <[email protected]> Trust: Filippo Valsorda <[email protected]> TryBot-Result: Gopher Robot <[email protected]> Reviewed-by: Roland Shoemaker <[email protected]>
1 parent 4aacb7f commit c18f398

File tree

3 files changed

+23
-1
lines changed

3 files changed

+23
-1
lines changed

src/crypto/rand/util.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
package rand
66

77
import (
8+
"crypto/internal/randutil"
89
"errors"
910
"io"
1011
"math/big"
@@ -17,6 +18,8 @@ func Prime(rand io.Reader, bits int) (*big.Int, error) {
1718
return nil, errors.New("crypto/rand: prime size must be at least 2-bit")
1819
}
1920

21+
randutil.MaybeReadByte(rand)
22+
2023
b := uint(bits % 8)
2124
if b == 0 {
2225
b = 8

src/crypto/rand/util_test.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,25 @@ func TestPrimeBitsLt2(t *testing.T) {
3838
}
3939
}
4040

41+
func TestPrimeNondeterministic(t *testing.T) {
42+
r := mathrand.New(mathrand.NewSource(42))
43+
p0, err := rand.Prime(r, 32)
44+
if err != nil {
45+
t.Fatal(err)
46+
}
47+
for i := 0; i < 128; i++ {
48+
r.Seed(42)
49+
p, err := rand.Prime(r, 32)
50+
if err != nil {
51+
t.Fatal(err)
52+
}
53+
if p.Cmp(p0) != 0 {
54+
return
55+
}
56+
}
57+
t.Error("Prime always generated the same prime given the same input")
58+
}
59+
4160
func TestInt(t *testing.T) {
4261
// start at 128 so the case of (max.BitLen() % 8) == 0 is covered
4362
for n := 128; n < 140; n++ {

src/go/build/deps_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -416,8 +416,8 @@ var depsRules = `
416416
417417
# CRYPTO-MATH is core bignum-based crypto - no cgo, net; fmt now ok.
418418
CRYPTO, FMT, math/big, embed
419-
< crypto/rand
420419
< crypto/internal/randutil
420+
< crypto/rand
421421
< crypto/ed25519
422422
< encoding/asn1
423423
< golang.org/x/crypto/cryptobyte/asn1

0 commit comments

Comments
 (0)