A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

crypt.py 2.6 KiB

13 vuotta sitten
13 vuotta sitten
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. # -*- coding: utf-8 -*-
  2. """
  3. Cryptography functions (hashing and cyphers) for EarwigBot IRC.
  4. """
  5. import hashlib
  6. from irc.classes 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. self.connection.reply(data, blowfish.encrypt(key, text))
  56. else:
  57. self.connection.reply(data, blowfish.decrypt(key, text))
  58. except blowfish.BlowfishError as error:
  59. self.connection.reply(data, "{0}: {1}.".format(
  60. error.__class__.__name__, error))