""" Psycho Key — Python SDK (v2 AES-256-GCM protocol) Requires: pip install cryptography Works with Python 3.8+ Usage: from psychokey import Client, Config client = Client(Config(app="my-app", api_secret="64hex...")) res = client.auth("PSYCHO-XXXX-XXXX-XXXX-XXXX") if res.ok: print(f"License active, {res.license.days_left} days left") """ from __future__ import annotations import hashlib import hmac import json import os import platform import re import secrets import subprocess import struct import time import urllib.request import urllib.error from dataclasses import dataclass, field from typing import Any, Dict, List, Optional # --------------------------------------------------------------------------- # HKDF-SHA256 (extract + expand, RFC 5869) # --------------------------------------------------------------------------- def _hkdf_extract(salt: bytes, ikm: bytes) -> bytes: return hmac.new(salt, ikm, "sha256").digest() def _hkdf_expand(prk: bytes, info: bytes, length: int) -> bytes: n = (length + 31) // 32 okm = b"" t = b"" for i in range(1, n + 1): t = hmac.new(prk, t + info + bytes([i]), "sha256").digest() okm += t return okm[:length] def _hkdf_sha256(ikm: bytes, salt: str, info: str, length: int = 32) -> bytes: prk = _hkdf_extract(salt.encode(), ikm) return _hkdf_expand(prk, info.encode(), length) # --------------------------------------------------------------------------- # AES-256-GCM (via cryptography library) # --------------------------------------------------------------------------- try: from cryptography.hazmat.primitives.ciphers.aead import AESGCM _HAS_CRYPTO = True except ImportError: _HAS_CRYPTO = False def _aes_gcm_encrypt(key: bytes, plaintext: bytes, aad: bytes) -> tuple: """Returns (iv, ciphertext, tag) all as bytes.""" if not _HAS_CRYPTO: raise RuntimeError("Install 'cryptography': pip install cryptography") iv = secrets.token_bytes(12) aes = AESGCM(key) ct_and_tag = aes.encrypt(iv, plaintext, aad) ct = ct_and_tag[:-16] tag = ct_and_tag[-16:] return iv, ct, tag def _aes_gcm_decrypt(key: bytes, iv: bytes, ct: bytes, tag: bytes, aad: bytes) -> bytes: """Decrypt and verify AES-256-GCM. Raises on auth failure.""" if not _HAS_CRYPTO: raise RuntimeError("Install 'cryptography': pip install cryptography") aes = AESGCM(key) return aes.decrypt(iv, ct + tag, aad) # --------------------------------------------------------------------------- # HWID detection # --------------------------------------------------------------------------- def _get_hwid() -> str: """Platform-specific hardware fingerprint matching ^[A-Za-z0-9:_-]{8,128}$.""" system = platform.system() cand = "" try: if system == "Windows": out = subprocess.check_output( ["wmic", "csproduct", "get", "UUID"], stderr=subprocess.DEVNULL, timeout=5 ).decode(errors="ignore").strip() lines = [l.strip() for l in out.splitlines() if l.strip() and l.strip() != "UUID"] if lines: cand = lines[0] elif system == "Linux": for path in ("/etc/machine-id", "/var/lib/dbus/machine-id"): if os.path.isfile(path): with open(path) as f: mid = f.read().strip() if mid: cand = mid break elif system == "Darwin": out = subprocess.check_output( ["ioreg", "-rd1", "-c", "IOPlatformExpertDevice"], stderr=subprocess.DEVNULL, timeout=5 ).decode(errors="ignore") for line in out.splitlines(): if "IOPlatformUUID" in line: parts = line.split('"') if len(parts) >= 4: cand = parts[-2].strip() break except Exception: pass if re.fullmatch(r"[A-Za-z0-9:_-]{8,128}", cand or ""): return cand # Fallback: hash of hostname + platform raw = f"{platform.node()}|{platform.system()}|{platform.machine()}" return hashlib.sha256(raw.encode()).hexdigest()[:32] # --------------------------------------------------------------------------- # Data classes # --------------------------------------------------------------------------- @dataclass class Config: app: str api_secret: str # 64 hex chars base_url: str = "https://psycho-key.com" version: str = "1.0.0" require_v2: bool = True @dataclass class License: id: int = 0 status: str = "" duration_days: int = 0 duration_seconds: int = 0 max_hwids: int = 0 activated_at: str = "" expires_at: str = "" days_left: int = -1 seconds_left: int = -1 lifetime: bool = False @dataclass class Result: ok: bool = False code: str = "" message: str = "" token: str = "" retry_after: int = 0 latest_version: str = "" download_url: str = "" variables: Dict[str, str] = field(default_factory=dict) license: License = field(default_factory=License) # --------------------------------------------------------------------------- # Client # --------------------------------------------------------------------------- class Client: def __init__(self, config: Config): self._config = config self._secret = bytes.fromhex(config.api_secret) if len(self._secret) != 32: raise ValueError("api_secret must be exactly 64 hex chars (32 bytes)") self._hwid = _get_hwid() self._token = "" self._vars: Dict[str, str] = {} def hwid(self) -> str: return self._hwid def var(self, key: str, default: str = "") -> str: return self._vars.get(key, default) # ----- Public API ----- def init(self) -> Result: """Handshake: check connectivity, product status, version.""" return self._call("init") def auth(self, license_key: str) -> Result: """Validate a license key and bind this machine's HWID.""" res = self._call("license", license_key=license_key) if res.ok and res.token: self._token = res.token if res.variables: self._vars.update(res.variables) return res def heartbeat(self) -> Result: """Keep the session alive and get updated license info.""" res = self._call("heartbeat") if res.ok and res.token: self._token = res.token if res.variables: self._vars.update(res.variables) return res def logout(self) -> Result: """Revoke the current session on the server.""" res = self._call("logout") self._token = "" return res def reset_hwid(self, license_key: str) -> Result: """Self-service HWID reset and rebind to this machine.""" res = self._call("reset", license_key=license_key) if res.ok and res.token: self._token = res.token if res.variables: self._vars.update(res.variables) return res # ----- Internal ----- def _call(self, action: str, license_key: str = "") -> Result: out = Result() try: nonce = secrets.token_hex(16) ts = int(time.time()) # HMAC signature canonical = "|".join([ self._config.app, action, nonce, str(ts), self._hwid, license_key, self._token, ]) sig = hmac.new(self._secret, canonical.encode(), "sha256").hexdigest() inner = json.dumps({ "action": action, "nonce": nonce, "ts": ts, "hwid": self._hwid, "license_key": license_key, "token": self._token, "version": self._config.version, "sig": sig, }, separators=(",", ":")) # Encrypt inner with AES-256-GCM req_key = _hkdf_sha256( self._secret, "psychokey-salt-v1", f"psychokey-req-v2|{self._config.app}" ) iv, ct, tag = _aes_gcm_encrypt(req_key, inner.encode(), self._config.app.encode()) import base64 envelope = json.dumps({ "app": self._config.app, "v": 2, "iv": base64.b64encode(iv).decode(), "ct": base64.b64encode(ct).decode(), "tag": base64.b64encode(tag).decode(), }, separators=(",", ":")) # HTTP POST url = self._config.base_url.rstrip("/") + "/api/v1.php" req = urllib.request.Request( url, data=envelope.encode(), method="POST", headers={ "Content-Type": "application/json", "User-Agent": f"PsychoKey-Python/{self._config.version}", }, ) try: with urllib.request.urlopen(req, timeout=15) as resp: body = resp.read() except urllib.error.HTTPError as e: body = e.read() root = json.loads(body) # Decrypt v2 response if root.get("v") == 2: resp_key = _hkdf_sha256( self._secret, "psychokey-salt-v1", f"psychokey-resp-v2|{self._config.app}" ) aad = f"{self._config.app}|{action}|{nonce}" plain = _aes_gcm_decrypt( resp_key, base64.b64decode(root["iv"]), base64.b64decode(root["ct"]), base64.b64decode(root["tag"]), aad.encode(), ) payload = json.loads(plain) else: # Pre-auth errors are unencrypted if root.get("success", False) and self._config.require_v2: out.code = "CLIENT_INTEGRITY" out.message = "Unencrypted success rejected." return out payload = root # Parse payload out.ok = payload.get("success", False) out.code = payload.get("code", "ERROR") out.message = payload.get("message", "") out.retry_after = int(payload.get("retry_after", 0)) out.latest_version = payload.get("latest_version", "") out.download_url = payload.get("download_url", "") if isinstance(payload.get("variables"), dict): out.variables = { k: str(v) for k, v in payload["variables"].items() if isinstance(v, str) } if out.ok: out.token = payload.get("token", "") lic = payload.get("license", {}) if isinstance(lic, dict): out.license = License( id=int(lic.get("id", 0)), status=lic.get("status", ""), duration_days=int(lic.get("duration", 0)), duration_seconds=int(lic.get("duration_seconds", 0)), max_hwids=int(lic.get("max_hwids", 0)), activated_at=lic.get("activated_at", ""), expires_at=lic.get("expires_at", ""), days_left=int(lic.get("days_left", -1)), seconds_left=int(lic.get("seconds_left", -1)), lifetime=bool(lic.get("lifetime", False)), ) except Exception as e: out.code = "CLIENT_ERROR" out.message = str(e) return out