]> Cypherpunks repositories - gostls13.git/commitdiff
crypto/elliptic: resample private keys if out of range.
authorAdam Langley <agl@golang.org>
Fri, 4 Dec 2015 22:17:03 +0000 (14:17 -0800)
committerRuss Cox <rsc@golang.org>
Tue, 8 Dec 2015 17:39:09 +0000 (17:39 +0000)
The orders of the curves in crypto/elliptic are all very close to a
power of two. None the less, there is a tiny bias in the private key
selection.

This change makes the distribution uniform by resampling in the case
that a private key is >= to the order of the curve. (It also switches
from using BitSize to Params().N.BitLen() because, although they're the
same value here, the latter is technically the correct thing to do.)

The private key sampling and nonce sampling in crypto/ecdsa don't have
this issue.

Fixes #11082.

Change-Id: Ie2aad563209a529fa1cab522abaf5fd505c7269a
Reviewed-on: https://go-review.googlesource.com/17460
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
Run-TryBot: Brad Fitzpatrick <bradfitz@golang.org>
Reviewed-by: Russ Cox <rsc@golang.org>
src/crypto/elliptic/elliptic.go

index e6b59c5f436b9d24a8a61e093bd2adcc079e72ba..c02df45d10502d129bf3bf48406593492d8d85c9 100644 (file)
@@ -274,7 +274,8 @@ var mask = []byte{0xff, 0x1, 0x3, 0x7, 0xf, 0x1f, 0x3f, 0x7f}
 // GenerateKey returns a public/private key pair. The private key is
 // generated using the given reader, which must return random data.
 func GenerateKey(curve Curve, rand io.Reader) (priv []byte, x, y *big.Int, err error) {
-       bitSize := curve.Params().BitSize
+       N := curve.Params().N
+       bitSize := N.BitLen()
        byteLen := (bitSize + 7) >> 3
        priv = make([]byte, byteLen)
 
@@ -289,6 +290,12 @@ func GenerateKey(curve Curve, rand io.Reader) (priv []byte, x, y *big.Int, err e
                // This is because, in tests, rand will return all zeros and we don't
                // want to get the point at infinity and loop forever.
                priv[1] ^= 0x42
+
+               // If the scalar is out of range, sample another random number.
+               if new(big.Int).SetBytes(priv).Cmp(N) >= 0 {
+                       continue
+               }
+
                x, y = curve.ScalarBaseMult(priv)
        }
        return