brain_hashlib.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. # Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
  2. # For details: https://github.com/PyCQA/astroid/blob/main/LICENSE
  3. # Copyright (c) https://github.com/PyCQA/astroid/blob/main/CONTRIBUTORS.txt
  4. from astroid.brain.helpers import register_module_extender
  5. from astroid.builder import parse
  6. from astroid.const import PY39_PLUS
  7. from astroid.manager import AstroidManager
  8. def _hashlib_transform():
  9. maybe_usedforsecurity = ", usedforsecurity=True" if PY39_PLUS else ""
  10. init_signature = f"value=''{maybe_usedforsecurity}"
  11. digest_signature = "self"
  12. shake_digest_signature = "self, length"
  13. template = """
  14. class %(name)s:
  15. def __init__(self, %(init_signature)s): pass
  16. def digest(%(digest_signature)s):
  17. return %(digest)s
  18. def copy(self):
  19. return self
  20. def update(self, value): pass
  21. def hexdigest(%(digest_signature)s):
  22. return ''
  23. @property
  24. def name(self):
  25. return %(name)r
  26. @property
  27. def block_size(self):
  28. return 1
  29. @property
  30. def digest_size(self):
  31. return 1
  32. """
  33. algorithms_with_signature = dict.fromkeys(
  34. [
  35. "md5",
  36. "sha1",
  37. "sha224",
  38. "sha256",
  39. "sha384",
  40. "sha512",
  41. "sha3_224",
  42. "sha3_256",
  43. "sha3_384",
  44. "sha3_512",
  45. ],
  46. (init_signature, digest_signature),
  47. )
  48. blake2b_signature = (
  49. "data=b'', *, digest_size=64, key=b'', salt=b'', "
  50. "person=b'', fanout=1, depth=1, leaf_size=0, node_offset=0, "
  51. f"node_depth=0, inner_size=0, last_node=False{maybe_usedforsecurity}"
  52. )
  53. blake2s_signature = (
  54. "data=b'', *, digest_size=32, key=b'', salt=b'', "
  55. "person=b'', fanout=1, depth=1, leaf_size=0, node_offset=0, "
  56. f"node_depth=0, inner_size=0, last_node=False{maybe_usedforsecurity}"
  57. )
  58. shake_algorithms = dict.fromkeys(
  59. ["shake_128", "shake_256"],
  60. (init_signature, shake_digest_signature),
  61. )
  62. algorithms_with_signature.update(shake_algorithms)
  63. algorithms_with_signature.update(
  64. {
  65. "blake2b": (blake2b_signature, digest_signature),
  66. "blake2s": (blake2s_signature, digest_signature),
  67. }
  68. )
  69. classes = "".join(
  70. template
  71. % {
  72. "name": hashfunc,
  73. "digest": 'b""',
  74. "init_signature": init_signature,
  75. "digest_signature": digest_signature,
  76. }
  77. for hashfunc, (
  78. init_signature,
  79. digest_signature,
  80. ) in algorithms_with_signature.items()
  81. )
  82. return parse(classes)
  83. register_module_extender(AstroidManager(), "hashlib", _hashlib_transform)