microblog.pub/utils/key.py

43 lines
1.1 KiB
Python
Raw Normal View History

2018-05-18 18:41:41 +00:00
import binascii
2018-06-16 20:02:10 +00:00
import os
2018-05-29 19:36:05 +00:00
from typing import Callable
2018-05-18 18:41:41 +00:00
2018-06-16 19:24:53 +00:00
from little_boxes.key import Key
KEY_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "config")
2018-05-18 18:41:41 +00:00
2018-05-29 19:36:05 +00:00
def _new_key() -> str:
2018-06-16 19:24:53 +00:00
return binascii.hexlify(os.urandom(32)).decode("utf-8")
2018-05-29 19:36:05 +00:00
def get_secret_key(name: str, new_key: Callable[[], str] = _new_key) -> str:
2018-06-16 19:24:53 +00:00
"""Loads or generates a cryptographic key."""
key_path = os.path.join(KEY_DIR, f"{name}.key")
2018-05-18 18:41:41 +00:00
if not os.path.exists(key_path):
2018-05-29 19:36:05 +00:00
k = new_key()
2018-06-16 19:24:53 +00:00
with open(key_path, "w+") as f:
2018-05-18 18:41:41 +00:00
f.write(k)
return k
with open(key_path) as f:
return f.read()
2019-04-17 21:33:15 +00:00
def get_key(owner: str, _id: str, user: str, domain: str) -> Key:
2018-06-16 19:24:53 +00:00
""""Loads or generates an RSA key."""
2019-04-17 21:33:15 +00:00
k = Key(owner, _id)
2018-06-16 19:24:53 +00:00
user = user.replace(".", "_")
domain = domain.replace(".", "_")
key_path = os.path.join(KEY_DIR, f"key_{user}_{domain}.pem")
if os.path.isfile(key_path):
with open(key_path) as f:
privkey_pem = f.read()
k.load(privkey_pem)
else:
k.new()
with open(key_path, "w") as f:
f.write(k.privkey_pem)
return k