Skip to content

bpo-45150: add a simple file_digest helper #28252

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 22 additions & 1 deletion Lib/hashlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,8 @@
algorithms_available = set(__always_supported)

__all__ = __always_supported + ('new', 'algorithms_guaranteed',
'algorithms_available', 'pbkdf2_hmac')
'algorithms_available', 'pbkdf2_hmac',
'file_digest')


__builtin_constructor_cache = {}
Expand Down Expand Up @@ -254,6 +255,22 @@ def prf(msg, inner=inner, outer=outer):
pass


def file_digest(filepath, digest=None, chunk_size=4096, hex=True):
"""Returns a digest of a file.
"""
if digest is None:
from _sha256 import sha256
digest = sha256

hash = digest()
with open(filepath, "rb") as f:
for chunk in iter(lambda: f.read(chunk_size), b""):
hash.update(chunk)
if hex:
return hash.hexdigest()
return hash.digest()


for __func_name in __always_supported:
# try them all, some may not work due to the OpenSSL
# version not supporting that algorithm.
Expand All @@ -263,6 +280,10 @@ def prf(msg, inner=inner, outer=outer):
import logging
logging.exception('code for hash %s was not found.', __func_name)

if __name__ == '__main__':
import sys

print(file_digest(sys.argv[1]))

# Cleanup locals()
del __always_supported, __func_name, __get_hash
Expand Down