Skip to content

Commit 5b874ee

Browse files
bradfitzadg
authored andcommitted
crypto/rsa, crypto/ecdsa: fail earlier on zero parameters
Change-Id: Ia6ed49d5ef3a256a55e6d4eaa1b4d9f0fc447013 Reviewed-on: https://go-review.googlesource.com/21560 Reviewed-by: Robert Griesemer <[email protected]> Reviewed-on: https://go-review.googlesource.com/21638 Reviewed-by: Brad Fitzpatrick <[email protected]> Run-TryBot: Andrew Gerrand <[email protected]>
1 parent 2cfbb87 commit 5b874ee

File tree

2 files changed

+12
-4
lines changed

2 files changed

+12
-4
lines changed

src/crypto/ecdsa/ecdsa.go

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import (
2323
"crypto/elliptic"
2424
"crypto/sha512"
2525
"encoding/asn1"
26+
"errors"
2627
"io"
2728
"math/big"
2829
)
@@ -129,6 +130,8 @@ func fermatInverse(k, N *big.Int) *big.Int {
129130
return new(big.Int).Exp(k, nMinus2, N)
130131
}
131132

133+
var errZeroParam = errors.New("zero parameter")
134+
132135
// Sign signs an arbitrary length hash (which should be the result of hashing a
133136
// larger message) using the private key, priv. It returns the signature as a
134137
// pair of integers. The security of the private key depends on the entropy of
@@ -169,7 +172,9 @@ func Sign(rand io.Reader, priv *PrivateKey, hash []byte) (r, s *big.Int, err err
169172
// See [NSA] 3.4.1
170173
c := priv.PublicKey.Curve
171174
N := c.Params().N
172-
175+
if N.Sign() == 0 {
176+
return nil, nil, errZeroParam
177+
}
173178
var k, kInv *big.Int
174179
for {
175180
for {
@@ -179,7 +184,7 @@ func Sign(rand io.Reader, priv *PrivateKey, hash []byte) (r, s *big.Int, err err
179184
return
180185
}
181186

182-
kInv = fermatInverse(k, N)
187+
kInv = fermatInverse(k, N) // N != 0
183188
r, _ = priv.Curve.ScalarBaseMult(k.Bytes())
184189
r.Mod(r, N)
185190
if r.Sign() != 0 {
@@ -191,7 +196,7 @@ func Sign(rand io.Reader, priv *PrivateKey, hash []byte) (r, s *big.Int, err err
191196
s = new(big.Int).Mul(priv.D, r)
192197
s.Add(s, e)
193198
s.Mul(s, kInv)
194-
s.Mod(s, N)
199+
s.Mod(s, N) // N != 0
195200
if s.Sign() != 0 {
196201
break
197202
}

src/crypto/rsa/rsa.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -436,6 +436,9 @@ func decrypt(random io.Reader, priv *PrivateKey, c *big.Int) (m *big.Int, err er
436436
err = ErrDecryption
437437
return
438438
}
439+
if priv.N.Sign() == 0 {
440+
return nil, ErrDecryption
441+
}
439442

440443
var ir *big.Int
441444
if random != nil {
@@ -461,7 +464,7 @@ func decrypt(random io.Reader, priv *PrivateKey, c *big.Int) (m *big.Int, err er
461464
}
462465
}
463466
bigE := big.NewInt(int64(priv.E))
464-
rpowe := new(big.Int).Exp(r, bigE, priv.N)
467+
rpowe := new(big.Int).Exp(r, bigE, priv.N) // N != 0
465468
cCopy := new(big.Int).Set(c)
466469
cCopy.Mul(cCopy, rpowe)
467470
cCopy.Mod(cCopy, priv.N)

0 commit comments

Comments
 (0)