secforge / app /utils /crypto.py
rk147's picture
Update app/utils/crypto.py
b845721 verified
Raw History Blame Contribute Delete
1.72 kB
"""AES-based encryption for session data using password."""
import os
import json
import base64
import hashlib
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
def _derive_key(password: str, salt: bytes) -> bytes:
"""Derive a 32-byte AES key from password + salt using PBKDF2."""
return hashlib.pbkdf2_hmac(
"sha256",
password.encode("utf-8"),
salt,
iterations=100_000,
dklen=32,
)
def derive_session_id(password: str) -> str:
"""
Derive a deterministic session ID from the password.
Same password always gives the same session ID.
"""
return hashlib.sha256(f"secforge::{password}".encode()).hexdigest()[:16]
def encrypt(data: dict, password: str) -> str:
"""Encrypt a dict to a base64 string using AES-GCM."""
salt = os.urandom(16)
key = _derive_key(password, salt)
aesgcm = AESGCM(key)
nonce = os.urandom(12)
plaintext = json.dumps(data).encode("utf-8")
ciphertext = aesgcm.encrypt(nonce, plaintext, None)
# Pack: salt(16) + nonce(12) + ciphertext
packed = salt + nonce + ciphertext
return base64.b64encode(packed).decode("utf-8")
def decrypt(token: str, password: str) -> dict:
"""Decrypt a base64 token back to dict. Raises ValueError on wrong password."""
try:
packed = base64.b64decode(token.encode("utf-8"))
salt = packed[:16]
nonce = packed[16:28]
ciphertext = packed[28:]
key = _derive_key(password, salt)
aesgcm = AESGCM(key)
plaintext = aesgcm.decrypt(nonce, ciphertext, None)
return json.loads(plaintext.decode("utf-8"))
except Exception:
raise ValueError("Wrong password or corrupted data.")