File size: 1,673 Bytes
6a8d4c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
"""Passwords (PBKDF2, stdlib), JWT sessions (PyJWT), and Fernet encryption for exchange keys."""
from __future__ import annotations

import base64
import hashlib
import hmac
import os
import secrets
import time
from typing import Optional

import jwt
from cryptography.fernet import Fernet

SECRET = os.environ.get("QRYPTO_SECRET")
if not SECRET:
    # Dev fallback. In production set QRYPTO_SECRET (any long random string) as an environment secret.
    SECRET = "dev-only-" + hashlib.sha256(b"qrypto-dev").hexdigest()

_FERNET = Fernet(base64.urlsafe_b64encode(hashlib.sha256(SECRET.encode()).digest()))
JWT_TTL = 60 * 60 * 24 * 30


def hash_password(pw: str) -> str:
    salt = secrets.token_bytes(16)
    dk = hashlib.pbkdf2_hmac("sha256", pw.encode(), salt, 200_000)
    return base64.b64encode(salt).decode() + "$" + base64.b64encode(dk).decode()


def verify_password(pw: str, stored: str) -> bool:
    try:
        salt_b64, dk_b64 = stored.split("$")
        salt, dk = base64.b64decode(salt_b64), base64.b64decode(dk_b64)
    except Exception:
        return False
    cand = hashlib.pbkdf2_hmac("sha256", pw.encode(), salt, 200_000)
    return hmac.compare_digest(cand, dk)


def issue_token(uid: str) -> str:
    return jwt.encode({"sub": uid, "iat": int(time.time()), "exp": int(time.time()) + JWT_TTL}, SECRET, algorithm="HS256")


def read_token(token: str) -> Optional[str]:
    try:
        return jwt.decode(token, SECRET, algorithms=["HS256"])["sub"]
    except jwt.PyJWTError:
        return None


def encrypt(s: str) -> str:
    return _FERNET.encrypt(s.encode()).decode()


def decrypt(s: str) -> str:
    return _FERNET.decrypt(s.encode()).decode()