A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

crypt.py 2.9 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. # -*- coding: utf-8 -*-
  2. """
  3. Cryptography functions (hashing and cyphers) for EarwigBot IRC.
  4. """
  5. import hashlib
  6. from irc.base_command import BaseCommand
  7. from lib import blowfish
  8. class Cryptography(BaseCommand):
  9. def get_hooks(self):
  10. return ["msg"]
  11. def get_help(self, command):
  12. if command == "hash":
  13. return ("Return the hash of a string using a given algorithm, " +
  14. "e.g. '!hash sha512 Hello world!'. Use '!hash list' for " +
  15. "a list of supported algorithms.")
  16. elif command == "encrypt":
  17. return ("Encrypt any string with a given key using an " +
  18. "implementation of Blowfish, e.g. '!encrypt some_key " +
  19. "Hello!'.")
  20. else:
  21. return ("Decrypt any string with a given key using an " +
  22. "implementation of Blowfish, e.g. '!decrypt some_key " +
  23. "762cee8a5239548af18275d6c1184f16'.")
  24. def check(self, data):
  25. if data.is_command and data.command in ["hash", "encrypt", "decrypt"]:
  26. return True
  27. return False
  28. def process(self, data):
  29. if not data.args:
  30. self.connection.reply(data, "what do you want me to {0}?".format(
  31. data.command))
  32. return
  33. if data.command == "hash":
  34. algo = data.args[0]
  35. if algo == "list":
  36. algos = ', '.join(hashlib.algorithms)
  37. self.connection.reply(data, "supported algorithms: " + algos +
  38. ".")
  39. elif algo in hashlib.algorithms:
  40. string = ' '.join(data.args[1:])
  41. result = eval("hashlib.{0}(string)".format(algo)).hexdigest()
  42. self.connection.reply(data, result)
  43. else:
  44. self.connection.reply(data, "unknown algorithm: '{0}'.".format(
  45. algo))
  46. else:
  47. key = data.args[0]
  48. text = ' '.join(data.args[1:])
  49. if not text:
  50. self.connection.reply(data, ("a key was provided, but text " +
  51. "to {0} was not.").format(data.command))
  52. return
  53. try:
  54. if data.command == "encrypt":
  55. result = blowfish.encrypt(key, text)
  56. else:
  57. result = blowfish.decrypt(key, text)
  58. except blowfish.KeyTooShortError:
  59. self.connection.reply(data, "key is too short.")
  60. except blowfish.KeyTooLongError:
  61. self.connection.reply(data, "key is too long.")
  62. except blowfish.IncorrectKeyError:
  63. self.connection.reply(data, "key is incorrect!")
  64. except blowfish.BadCyphertextError as e:
  65. self.connection.reply(data, "bad cyphertext: {0}.".format(e))
  66. else:
  67. self.connection.reply(data, result)