Mercurial > repos > guerler > springsuite
comparison planemo/lib/python3.7/site-packages/galaxy/util/hash_util.py @ 1:56ad4e20f292 draft
"planemo upload commit 6eee67778febed82ddd413c3ca40b3183a3898f1"
| author | guerler |
|---|---|
| date | Fri, 31 Jul 2020 00:32:28 -0400 |
| parents | |
| children |
comparison
equal
deleted
inserted
replaced
| 0:d30785e31577 | 1:56ad4e20f292 |
|---|---|
| 1 """ | |
| 2 Utility functions for bi-directional Python version compatibility. Python 2.5 | |
| 3 introduced hashlib which replaced sha in Python 2.4 and previous versions. | |
| 4 """ | |
| 5 from __future__ import absolute_import | |
| 6 | |
| 7 import hashlib | |
| 8 import hmac | |
| 9 import logging | |
| 10 | |
| 11 from . import smart_str | |
| 12 | |
| 13 | |
| 14 log = logging.getLogger(__name__) | |
| 15 | |
| 16 BLOCK_SIZE = 1024 * 1024 | |
| 17 | |
| 18 sha1 = hashlib.sha1 | |
| 19 sha256 = hashlib.sha256 | |
| 20 sha512 = hashlib.sha512 | |
| 21 sha = sha1 | |
| 22 md5 = hashlib.md5 | |
| 23 | |
| 24 HASH_NAME_MAP = { | |
| 25 "MD5": md5, | |
| 26 "SHA-1": sha1, | |
| 27 "SHA-256": sha256, | |
| 28 "SHA-512": sha512, | |
| 29 } | |
| 30 HASH_NAMES = list(HASH_NAME_MAP.keys()) | |
| 31 | |
| 32 | |
| 33 def memory_bound_hexdigest(hash_func=None, hash_func_name=None, path=None, file=None): | |
| 34 if hash_func is None: | |
| 35 assert hash_func_name is not None | |
| 36 hash_func = HASH_NAME_MAP[hash_func_name] | |
| 37 | |
| 38 hasher = hash_func() | |
| 39 if file is None: | |
| 40 assert path is not None | |
| 41 file = open(path, "rb") | |
| 42 else: | |
| 43 assert path is None, "Cannot specify path and path keyword arguments." | |
| 44 | |
| 45 try: | |
| 46 for block in iter(lambda: file.read(BLOCK_SIZE), b''): | |
| 47 hasher.update(block) | |
| 48 return hasher.hexdigest() | |
| 49 finally: | |
| 50 file.close() | |
| 51 | |
| 52 | |
| 53 def md5_hash_file(path): | |
| 54 """ | |
| 55 Return a md5 hashdigest for a file or None if path could not be read. | |
| 56 """ | |
| 57 hasher = hashlib.md5() | |
| 58 try: | |
| 59 with open(path, 'rb') as afile: | |
| 60 buf = afile.read() | |
| 61 hasher.update(buf) | |
| 62 return hasher.hexdigest() | |
| 63 except IOError: | |
| 64 # This may happen if path has been deleted | |
| 65 return None | |
| 66 | |
| 67 | |
| 68 def new_secure_hash(text_type): | |
| 69 """ | |
| 70 Returns the hexdigest of the sha1 hash of the argument `text_type`. | |
| 71 """ | |
| 72 assert text_type is not None | |
| 73 return sha1(smart_str(text_type)).hexdigest() | |
| 74 | |
| 75 | |
| 76 def hmac_new(key, value): | |
| 77 return hmac.new(key, value, sha).hexdigest() | |
| 78 | |
| 79 | |
| 80 def is_hashable(value): | |
| 81 try: | |
| 82 hash(value) | |
| 83 except Exception: | |
| 84 return False | |
| 85 return True | |
| 86 | |
| 87 | |
| 88 __all__ = ('md5', 'hashlib', 'sha1', 'sha', 'new_secure_hash', 'hmac_new', 'is_hashable') |
