microblog.pub/utils/key.py

47 lines
1.5 KiB
Python
Raw Normal View History

2018-05-18 13:41:41 -05:00
import os
import binascii
from Crypto.PublicKey import RSA
2018-05-29 14:36:05 -05:00
from typing import Callable
2018-05-18 13:41:41 -05:00
2018-05-30 15:50:45 -05:00
KEY_DIR = os.path.join(
os.path.dirname(os.path.abspath(__file__)), '..', 'config'
)
2018-05-18 13:41:41 -05:00
2018-05-29 14:36:05 -05:00
def _new_key() -> str:
return binascii.hexlify(os.urandom(32)).decode('utf-8')
def get_secret_key(name: str, new_key: Callable[[], str] = _new_key) -> str:
2018-05-30 16:57:14 -05:00
key_path = os.path.join(KEY_DIR, f'{name}.key')
2018-05-18 13:41:41 -05:00
if not os.path.exists(key_path):
2018-05-29 14:36:05 -05:00
k = new_key()
2018-05-18 13:41:41 -05:00
with open(key_path, 'w+') as f:
f.write(k)
return k
with open(key_path) as f:
return f.read()
class Key(object):
2018-06-01 13:29:44 -05:00
DEFAULT_KEY_SIZE = 2048
2018-05-18 13:41:41 -05:00
def __init__(self, user: str, domain: str, create: bool = True) -> None:
user = user.replace('.', '_')
domain = domain.replace('.', '_')
2018-05-30 16:57:14 -05:00
key_path = os.path.join(KEY_DIR, f'key_{user}_{domain}.pem')
2018-05-18 13:41:41 -05:00
if os.path.isfile(key_path):
with open(key_path) as f:
self.privkey_pem = f.read()
self.privkey = RSA.importKey(self.privkey_pem)
self.pubkey_pem = self.privkey.publickey().exportKey('PEM').decode('utf-8')
else:
if not create:
raise Exception('must init private key first')
2018-06-01 13:29:44 -05:00
k = RSA.generate(self.DEFAULT_KEY_SIZE)
2018-05-18 13:41:41 -05:00
self.privkey_pem = k.exportKey('PEM').decode('utf-8')
self.pubkey_pem = k.publickey().exportKey('PEM').decode('utf-8')
with open(key_path, 'w') as f:
f.write(self.privkey_pem)
self.privkey = k