Skip to content

Commit 886fba5

Browse files
FiloSottilegopherbot
authored andcommitted
crypto/ecdsa: properly truncate P-521 hashes
Before, if a hash was exactly 66 bytes long, we weren't truncating it for use with P-521, because the byte length was not overflowing. However, the bit length could still overflow. Fixes #60741 Change-Id: I37a0ee210add0eb566e6dc1c141e83e992983eb6 Reviewed-on: https://go-review.googlesource.com/c/go/+/502478 Auto-Submit: Filippo Valsorda <[email protected]> Reviewed-by: Roland Shoemaker <[email protected]> TryBot-Result: Gopher Robot <[email protected]> Run-TryBot: Filippo Valsorda <[email protected]> Reviewed-by: Damien Neil <[email protected]>
1 parent bce7aec commit 886fba5

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

src/crypto/ecdsa/ecdsa.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -380,7 +380,7 @@ func hashToNat[Point nistPoint[Point]](c *nistCurve[Point], e *bigmod.Nat, hash
380380
// an integer modulo N. This is the absolute worst of all worlds: we still
381381
// have to reduce, because the result might still overflow N, but to take
382382
// the left-most bits for P-521 we have to do a right shift.
383-
if size := c.N.Size(); len(hash) > size {
383+
if size := c.N.Size(); len(hash) >= size {
384384
hash = hash[:size]
385385
if excess := len(hash)*8 - c.N.BitLen(); excess > 0 {
386386
hash = bytes.Clone(hash)

src/crypto/ecdsa/ecdsa_test.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99
"bytes"
1010
"compress/bzip2"
1111
"crypto/elliptic"
12+
"crypto/internal/bigmod"
1213
"crypto/rand"
1314
"crypto/sha1"
1415
"crypto/sha256"
@@ -398,6 +399,20 @@ func testRandomPoint[Point nistPoint[Point]](t *testing.T, c *nistCurve[Point])
398399
}
399400
}
400401

402+
func TestHashToNat(t *testing.T) {
403+
t.Run("P-224", func(t *testing.T) { testHashToNat(t, p224()) })
404+
t.Run("P-256", func(t *testing.T) { testHashToNat(t, p256()) })
405+
t.Run("P-384", func(t *testing.T) { testHashToNat(t, p384()) })
406+
t.Run("P-521", func(t *testing.T) { testHashToNat(t, p521()) })
407+
}
408+
409+
func testHashToNat[Point nistPoint[Point]](t *testing.T, c *nistCurve[Point]) {
410+
for l := 0; l < 600; l++ {
411+
h := bytes.Repeat([]byte{0xff}, l)
412+
hashToNat(c, bigmod.NewNat(), h)
413+
}
414+
}
415+
401416
func TestZeroSignature(t *testing.T) {
402417
testAllCurves(t, testZeroSignature)
403418
}

0 commit comments

Comments
 (0)