Skip to content

Commit 33d59da

Browse files
authored
Merge pull request #215 from tomato42/fix-truncation
fix truncation of hash input with order bit size not multiple of 8
2 parents 23a5b65 + ccff823 commit 33d59da

File tree

1 file changed

+18
-4
lines changed

1 file changed

+18
-4
lines changed

src/ecdsa/keys.py

+18-4
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@
7777
from .numbertheory import square_root_mod_prime, SquareRootError
7878
from .ecdsa import RSZeroError
7979
from .util import string_to_number, number_to_string, randrange
80-
from .util import sigencode_string, sigdecode_string
80+
from .util import sigencode_string, sigdecode_string, bit_length
8181
from .util import (
8282
oid_ecPublicKey,
8383
encoded_oid_ecPublicKey,
@@ -717,14 +717,28 @@ def verify_digest(
717717
# signature doesn't have to be a bytes-like-object so don't normalise
718718
# it, the decoders will do that
719719
digest = normalise_bytes(digest)
720-
if allow_truncate:
721-
digest = digest[: self.curve.baselen]
722-
if len(digest) > self.curve.baselen:
720+
if not allow_truncate and len(digest) > self.curve.baselen:
723721
raise BadDigestError(
724722
"this curve (%s) is too short "
725723
"for your digest (%d)" % (self.curve.name, 8 * len(digest))
726724
)
727725
number = string_to_number(digest)
726+
if allow_truncate:
727+
max_length = bit_length(self.curve.order)
728+
# we don't use bit_length(number) as that truncates leading zeros
729+
length = len(digest) * 8
730+
731+
# See NIST FIPS 186-4:
732+
#
733+
# When the length of the output of the hash function is greater
734+
# than N (i.e., the bit length of q), then the leftmost N bits of
735+
# the hash function output block shall be used in any calculation
736+
# using the hash function output during the generation or
737+
# verification of a digital signature.
738+
#
739+
# as such, we need to shift-out the low-order bits:
740+
number >>= max(0, length - max_length)
741+
728742
try:
729743
r, s = sigdecode(signature, self.pubkey.order)
730744
except (der.UnexpectedDER, MalformedSignature) as e:

0 commit comments

Comments
 (0)