crypto/ecdsa: check the hash length in PrivateKey.Sign

Unfortunately, SignASN1 doesn't take the hash function at all, but
PrivateKey.Sign does, so we can check the hash length there.

This is arguably a breaking change, but the previous behavior is almost
certain to be a bug.

opts was allowed to be nil, so continue to allow that.

Change-Id: I75a11ab3f9df9de4234b1fc913f26ab06a6a6964
Reviewed-on: https://go-review.googlesource.com/c/go/+/765641
Reviewed-by: David Chase <drchase@google.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
Reviewed-by: Mark Freeman <markfreeman@google.com>
Reviewed-by: Daniel McCarney <daniel@binaryparadox.net>
Auto-Submit: Filippo Valsorda <filippo@golang.org>
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
This commit is contained in:
Filippo Valsorda 2026-04-11 14:43:36 +02:00 committed by Gopher Robot
parent 2f9a9642e1
commit 7f4f2c1c7b
3 changed files with 8 additions and 1 deletions

View file

@ -0,0 +1,2 @@
[PrivateKey.Sign] now checks that the length of the hash is correct, if opts is
not nil.

View file

@ -324,6 +324,11 @@ func (priv *PrivateKey) Sign(random io.Reader, digest []byte, opts crypto.Signer
if random == nil {
return signRFC6979(priv, digest, opts)
}
if opts != nil {
if hashSize := opts.HashFunc().Size(); hashSize != len(digest) {
return nil, errors.New("ecdsa: hash length does not match hash function")
}
}
random = rand.CustomReader(random)
return SignASN1(random, priv, digest)
}

View file

@ -274,7 +274,7 @@ type Signature struct {
R, S []byte
}
// Sign signs a hash (which shall be the result of hashing a larger message with
// Sign signs a hash (which should be the result of hashing a larger message with
// the hash function H) using the private key, priv. If the hash is longer than
// the bit-length of the private key's curve order, the hash will be truncated
// to that length.