key.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import binascii
  2. import os
  3. from typing import Callable
  4. from little_boxes.key import Key
  5. KEY_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "config")
  6. def _new_key() -> str:
  7. return binascii.hexlify(os.urandom(32)).decode("utf-8")
  8. def get_secret_key(name: str, new_key: Callable[[], str] = _new_key) -> str:
  9. """Loads or generates a cryptographic key."""
  10. key_path = os.path.join(KEY_DIR, f"{name}.key")
  11. if not os.path.exists(key_path):
  12. k = new_key()
  13. with open(key_path, "w+") as f:
  14. f.write(k)
  15. return k
  16. with open(key_path) as f:
  17. return f.read()
  18. def get_key(owner: str, user: str, domain: str) -> Key:
  19. """"Loads or generates an RSA key."""
  20. k = Key(owner)
  21. user = user.replace(".", "_")
  22. domain = domain.replace(".", "_")
  23. key_path = os.path.join(KEY_DIR, f"key_{user}_{domain}.pem")
  24. if os.path.isfile(key_path):
  25. with open(key_path) as f:
  26. privkey_pem = f.read()
  27. k.load(privkey_pem)
  28. else:
  29. k.new()
  30. with open(key_path, "w") as f:
  31. f.write(k.privkey_pem)
  32. return k