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.

104 lines
4.3 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2009-2015 Ben Kurtovic <ben.kurtovic@gmail.com>
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a copy
  6. # of this software and associated documentation files (the "Software"), to deal
  7. # in the Software without restriction, including without limitation the rights
  8. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. # copies of the Software, and to permit persons to whom the Software is
  10. # furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in
  13. # all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  21. # SOFTWARE.
  22. import base64
  23. import hashlib
  24. import os
  25. from earwigbot import importer
  26. from earwigbot.commands import Command
  27. fernet = importer.new("cryptography.fernet")
  28. hashes = importer.new("cryptography.hazmat.primitives.hashes")
  29. pbkdf2 = importer.new("cryptography.hazmat.primitives.kdf.pbkdf2")
  30. class Crypt(Command):
  31. """Provides hash functions with !hash (!hash list for supported algorithms)
  32. and basic encryption with !encrypt and !decrypt."""
  33. name = "crypt"
  34. commands = ["crypt", "hash", "encrypt", "decrypt"]
  35. def process(self, data):
  36. if data.command == "crypt":
  37. msg = "Available commands are !hash, !encrypt, and !decrypt."
  38. self.reply(data, msg)
  39. return
  40. if not data.args:
  41. msg = "What do you want me to {0}?".format(data.command)
  42. self.reply(data, msg)
  43. return
  44. if data.command == "hash":
  45. algo = data.args[0]
  46. if algo == "list":
  47. algos = ', '.join(hashlib.algorithms_available)
  48. msg = algos.join(("Supported algorithms: ", "."))
  49. self.reply(data, msg)
  50. elif algo in hashlib.algorithms_available:
  51. string = ' '.join(data.args[1:])
  52. result = getattr(hashlib, algo)(string.encode()).hexdigest()
  53. self.reply(data, result)
  54. else:
  55. msg = "Unknown algorithm: '{0}'.".format(algo)
  56. self.reply(data, msg)
  57. else:
  58. key = data.args[0]
  59. text = " ".join(data.args[1:])
  60. saltlen = 16
  61. if not text:
  62. msg = "A key was provided, but text to {0} was not."
  63. self.reply(data, msg.format(data.command))
  64. return
  65. try:
  66. if data.command == "encrypt":
  67. salt = os.urandom(saltlen)
  68. kdf = pbkdf2.PBKDF2HMAC(
  69. algorithm=hashes.SHA256(),
  70. length=32,
  71. salt=salt,
  72. iterations=100000,
  73. )
  74. f = fernet.Fernet(base64.urlsafe_b64encode(kdf.derive(key.encode())))
  75. ciphertext = f.encrypt(text.encode())
  76. self.reply(data, base64.b64encode(salt + ciphertext).decode())
  77. else:
  78. if len(text) < saltlen:
  79. raise ValueError("Ciphertext is too short")
  80. raw = base64.b64decode(text)
  81. salt, ciphertext = raw[:saltlen], raw[saltlen:]
  82. kdf = pbkdf2.PBKDF2HMAC(
  83. algorithm=hashes.SHA256(),
  84. length=32,
  85. salt=salt,
  86. iterations=100000,
  87. )
  88. f = fernet.Fernet(base64.urlsafe_b64encode(kdf.derive(key.encode())))
  89. self.reply(data, f.decrypt(ciphertext).decode())
  90. except ImportError:
  91. self.reply(data, "This command requires the 'cryptography' package: https://cryptography.io/")
  92. except Exception as error:
  93. self.reply(data, "{}: {}".format(type(error).__name__, str(error)))