brain_hashlib.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. # Copyright (c) 2016, 2018, 2020 Claudiu Popa <pcmanticore@gmail.com>
  2. # Copyright (c) 2018 David Poirier <david-poirier-csn@users.noreply.github.com>
  3. # Copyright (c) 2018 wgehalo <wgehalo@gmail.com>
  4. # Copyright (c) 2018 Ioana Tagirta <ioana.tagirta@gmail.com>
  5. # Copyright (c) 2020-2021 hippo91 <guillaume.peillex@gmail.com>
  6. # Copyright (c) 2020 David Gilman <davidgilman1@gmail.com>
  7. # Copyright (c) 2021 Pierre Sassoulas <pierre.sassoulas@gmail.com>
  8. # Copyright (c) 2021 Marc Mueller <30130371+cdce8p@users.noreply.github.com>
  9. # Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
  10. # For details: https://github.com/PyCQA/astroid/blob/main/LICENSE
  11. from astroid.brain.helpers import register_module_extender
  12. from astroid.builder import parse
  13. from astroid.manager import AstroidManager
  14. def _hashlib_transform():
  15. signature = "value=''"
  16. template = """
  17. class %(name)s(object):
  18. def __init__(self, %(signature)s): pass
  19. def digest(self):
  20. return %(digest)s
  21. def copy(self):
  22. return self
  23. def update(self, value): pass
  24. def hexdigest(self):
  25. return ''
  26. @property
  27. def name(self):
  28. return %(name)r
  29. @property
  30. def block_size(self):
  31. return 1
  32. @property
  33. def digest_size(self):
  34. return 1
  35. """
  36. algorithms_with_signature = dict.fromkeys(
  37. ["md5", "sha1", "sha224", "sha256", "sha384", "sha512"], signature
  38. )
  39. blake2b_signature = "data=b'', *, digest_size=64, key=b'', salt=b'', \
  40. person=b'', fanout=1, depth=1, leaf_size=0, node_offset=0, \
  41. node_depth=0, inner_size=0, last_node=False"
  42. blake2s_signature = "data=b'', *, digest_size=32, key=b'', salt=b'', \
  43. person=b'', fanout=1, depth=1, leaf_size=0, node_offset=0, \
  44. node_depth=0, inner_size=0, last_node=False"
  45. new_algorithms = dict.fromkeys(
  46. ["sha3_224", "sha3_256", "sha3_384", "sha3_512", "shake_128", "shake_256"],
  47. signature,
  48. )
  49. algorithms_with_signature.update(new_algorithms)
  50. algorithms_with_signature.update(
  51. {"blake2b": blake2b_signature, "blake2s": blake2s_signature}
  52. )
  53. classes = "".join(
  54. template % {"name": hashfunc, "digest": 'b""', "signature": signature}
  55. for hashfunc, signature in algorithms_with_signature.items()
  56. )
  57. return parse(classes)
  58. register_module_extender(AstroidManager(), "hashlib", _hashlib_transform)