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