hash_plugin.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # pylint: disable=missing-module-docstring, missing-class-docstring
  3. from __future__ import annotations
  4. import typing
  5. import re
  6. import hashlib
  7. from flask_babel import gettext
  8. from searx.plugins import Plugin, PluginInfo
  9. from searx.result_types import Answer
  10. if typing.TYPE_CHECKING:
  11. from searx.search import SearchWithPlugins
  12. from searx.extended_types import SXNG_Request
  13. class SXNGPlugin(Plugin):
  14. """Plugin converts strings to different hash digests. The results are
  15. displayed in area for the "answers".
  16. """
  17. id = "hash_plugin"
  18. default_on = True
  19. keywords = ["md5", "sha1", "sha224", "sha256", "sha384", "sha512"]
  20. def __init__(self):
  21. super().__init__()
  22. self.parser_re = re.compile(f"({'|'.join(self.keywords)}) (.*)", re.I)
  23. self.info = PluginInfo(
  24. id=self.id,
  25. name=gettext("Hash plugin"),
  26. description=gettext("Converts strings to different hash digests."),
  27. examples=["sha512 The quick brown fox jumps over the lazy dog"],
  28. preference_section="query",
  29. )
  30. def post_search(self, request: "SXNG_Request", search: "SearchWithPlugins") -> list[Answer]:
  31. """Returns a result list only for the first page."""
  32. results = []
  33. if search.search_query.pageno > 1:
  34. return results
  35. m = self.parser_re.match(search.search_query.query)
  36. if not m:
  37. # wrong query
  38. return results
  39. function, string = m.groups()
  40. if not string.strip():
  41. # end if the string is empty
  42. return results
  43. # select hash function
  44. f = hashlib.new(function.lower())
  45. # make digest from the given string
  46. f.update(string.encode("utf-8").strip())
  47. answer = function + " " + gettext("hash digest") + ": " + f.hexdigest()
  48. Answer(results=results, answer=answer)
  49. return results