Skip to content

Commit 275c3ab

Browse files
[3.15] gh-155419: honor the file object's current position in hashlib.file_digest (GH-155422) (#163081)
gh-155419: honor the file object's current position in `hashlib.file_digest` (GH-155422) (cherry picked from commit 5f6de00) Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com>
1 parent 778679d commit 275c3ab

3 files changed

Lines changed: 70 additions & 31 deletions

File tree

‎Lib/hashlib.py‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,8 @@
5353
'031edd7d41651593c5fe5c006fa5752b37fddff7bc4e843aa6af0c950f4b9406'
5454
"""
5555

56+
lazy import io
57+
5658
# This tuple and __get_builtin_constructor() must be modified if a new
5759
# always available algorithm is added.
5860
__always_supported = ('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512',
@@ -231,9 +233,10 @@ def file_digest(fileobj, digest, /, *, _bufsize=2**18):
231233
else:
232234
digestobj = digest()
233235

234-
if hasattr(fileobj, "getbuffer"):
236+
if isinstance(fileobj, io.BytesIO):
235237
# io.BytesIO object, use zero-copy buffer
236-
digestobj.update(fileobj.getbuffer())
238+
with fileobj.getbuffer() as buf:
239+
digestobj.update(buf[fileobj.tell():])
237240
return digestobj
238241

239242
# Only binary files implement readinto().

‎Lib/test/test_hashlib.py‎

Lines changed: 62 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
import itertools
1313
import logging
1414
import os
15+
import random
1516
import re
1617
import sys
1718
import sysconfig
@@ -23,7 +24,7 @@
2324
from test import support
2425
from test.support import _4G, bigmemtest
2526
from test.support import hashlib_helper
26-
from test.support.import_helper import import_fresh_module
27+
from test.support.import_helper import ensure_lazy_imports, import_fresh_module
2728
from test.support import requires_resource
2829
from test.support import threading_helper
2930
from http.client import HTTPException
@@ -125,6 +126,30 @@ def read_vectors(hash_name):
125126
)
126127

127128

129+
def make_hash_objects(*digestmods, buf=b"", **kwargs):
130+
objects = []
131+
for digestmod in digestmods:
132+
try:
133+
if callable(digestmod):
134+
obj = digestmod(buf)
135+
else:
136+
obj = hashlib.new(digestmod, buf, **kwargs)
137+
except ValueError:
138+
continue
139+
objects.append((digestmod, obj))
140+
return objects
141+
142+
143+
class BytesIOProxy:
144+
"""A file-like object with the io.BytesIO interface, not an io.BytesIO."""
145+
146+
def __init__(self, data):
147+
self._buffer = io.BytesIO(data)
148+
149+
def __getattr__(self, name):
150+
return getattr(self._buffer, name)
151+
152+
128153
class HashLibTestCase(unittest.TestCase):
129154
supported_hash_names = ( 'md5', 'MD5', 'sha1', 'SHA1',
130155
'sha224', 'SHA224', 'sha256', 'SHA256',
@@ -547,7 +572,8 @@ def test_blake2_update_over_4gb(self):
547572
self.assertEqual(h.hexdigest(), "8a268e83dd30528bc0907fa2008c91de8f090a0b6e0e60a5ff0d999d8485526f")
548573

549574
def check(self, name, data, hexdigest, shake=False, **kwargs):
550-
length = len(hexdigest)//2
575+
n = len(data)
576+
length = len(hexdigest) // 2
551577
hexdigest = hexdigest.lower()
552578
constructors = self.constructors_to_test[name]
553579
# 2 is for hashlib.name(...) and hashlib.new(name, ...)
@@ -556,47 +582,48 @@ def check(self, name, data, hexdigest, shake=False, **kwargs):
556582
m = hash_object_constructor(data, **kwargs)
557583
computed = m.hexdigest() if not shake else m.hexdigest(length)
558584
self.assertEqual(
559-
computed, hexdigest,
560-
"Hash algorithm %s constructed using %s returned hexdigest"
561-
" %r for %d byte input data that should have hashed to %r."
562-
% (name, hash_object_constructor,
563-
computed, len(data), hexdigest))
585+
computed, hexdigest,
586+
"Hash algorithm %s constructed using %s returned hexdigest"
587+
" %r for %d byte input data that should have hashed to %r."
588+
% (name, hash_object_constructor, computed, n, hexdigest)
589+
)
564590
computed = m.digest() if not shake else m.digest(length)
565591
digest = bytes.fromhex(hexdigest)
566592
self.assertEqual(computed, digest)
567593
if not shake:
568594
self.assertEqual(len(digest), m.digest_size)
569595

596+
def generate_sub_hexdigest(pos=-1):
597+
if pos < 0:
598+
pos = 0 if n == 0 else random.randrange(0, n)
599+
pos += 1 # ensure pos is at least 1 (allowed to be out of range)
600+
buf = data[pos:]
601+
objects = make_hash_objects(name, *constructors, buf=buf, **kwargs)
602+
hexdigests = {obj.hexdigest() for _, obj in objects}
603+
self.assertEqual(len(hexdigests), 1, f"bad digests: {objects}")
604+
return pos, hexdigests.pop()
605+
570606
if not shake and kwargs.get("key") is None:
571607
# skip shake and blake2 extended parameter tests
572608
self.check_file_digest(name, data, hexdigest)
609+
for pos in sorted({-1, 1, n - 1, n, n + 1}):
610+
with self.subTest(pos=pos):
611+
pos, hexdigest2 = generate_sub_hexdigest(pos=pos)
612+
self.check_file_digest(name, data, hexdigest2, pos)
573613

574-
def check_file_digest(self, name, data, hexdigest):
614+
def check_file_digest(self, name, data, hexdigest, pos=0):
575615
hexdigest = hexdigest.lower()
576-
digests = []
577-
for digest in [name, *self.constructors_to_test[name]]:
578-
try:
579-
if callable(digest):
580-
digest(b"")
581-
else:
582-
hashlib.new(digest)
583-
except ValueError:
584-
# skip, algorithm is blocked by security policy.
585-
continue
586-
digests.append(digest)
587-
616+
digests = make_hash_objects(name, *self.constructors_to_test[name])
588617
with tempfile.TemporaryFile() as f:
589618
f.write(data)
619+
buf = io.BytesIO(data)
620+
buf_like = BytesIOProxy(data)
590621

591-
for digest in digests:
592-
buf = io.BytesIO(data)
593-
buf.seek(0)
594-
self.assertEqual(
595-
hashlib.file_digest(buf, digest).hexdigest(), hexdigest
596-
)
597-
f.seek(0)
598-
digestobj = hashlib.file_digest(f, digest)
599-
self.assertEqual(digestobj.hexdigest(), hexdigest)
622+
for digest, _ in digests:
623+
for fobj in [buf, buf_like, f]:
624+
fobj.seek(pos)
625+
digestobj = hashlib.file_digest(fobj, digest)
626+
self.assertEqual(digestobj.hexdigest(), hexdigest)
600627

601628
def check_no_unicode(self, algorithm_name):
602629
# Unicode objects are not allowed as input.
@@ -1555,5 +1582,11 @@ def test_HACL_shake_attributes(self, size, attrname):
15551582
self.check_HACL_attribute(_sha3, f"shake_{size}", attrname)
15561583

15571584

1585+
@support.cpython_only
1586+
class LazyImportTest(unittest.TestCase):
1587+
def test_lazy_import(self):
1588+
ensure_lazy_imports("hashlib", {"io"})
1589+
1590+
15581591
if __name__ == "__main__":
15591592
unittest.main()
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Ensure that :func:`hashlib.file_digest` honors the current position of the
2+
file object when given an :class:`io.BytesIO` object. Patch by Bénédikt
3+
Tran.

0 commit comments

Comments
 (0)