qrypto-engine / api /security.py
Qempireautomation's picture
Add auth and key encryption
6a8d4c5 verified
Raw History Blame Contribute Delete
1.67 kB
"""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()