Files
plm-lottery/apps/lottery/seedbox.py
T

28 lines
956 B
Python
Raw Normal View History

"""A round's secret, encrypted at rest (DAT-64, RND-34).
The plaintext secret is written to the database only at the reveal; until then a copy of the database
alone must not tell who will win. Fernet with a key derived from `DJANGO_SECRET_KEY`. When the master
key file returns for the real engine (roadmap B4) this is where it plugs in.
"""
import base64
import hashlib
from cryptography.fernet import Fernet, InvalidToken
from django.conf import settings
def _fernet() -> Fernet:
key = hashlib.sha256(b"plm-lottery/round-seed/" + settings.SECRET_KEY.encode()).digest()
return Fernet(base64.urlsafe_b64encode(key))
def encrypt_seed(seed_hex: str) -> str:
return _fernet().encrypt(seed_hex.encode()).decode()
def decrypt_seed(token: str) -> str:
try:
return _fernet().decrypt(token.encode()).decode()
except InvalidToken as exc:
raise RuntimeError("the round secret cannot be decrypted with this key") from exc