File size: 1,723 Bytes
e78b484
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b845721
e78b484
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b845721
e78b484
 
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
"""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.")