// Psycho Key — C++ client SDK (Windows, self-contained) // Requires: Windows 10+, winhttp.lib, bcrypt.lib, advapi32.lib // // Usage: // psycho::Client client({"https://key.example.com", "my-product", "", "1.0.0"}); // auto res = client.auth(userKey); // if (!res.ok) { /* deny access */ } // // The API secret is the per-product secret from the panel. Treat it like a // password inside your binary. Pair with VMProtect/Themida for deeper protection. #pragma once #ifndef PSYCHOKEY_HPP #define PSYCHOKEY_HPP #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef _MSC_VER #pragma comment(lib, "winhttp.lib") #pragma comment(lib, "bcrypt.lib") #pragma comment(lib, "advapi32.lib") #pragma comment(lib, "crypt32.lib") #endif namespace psycho { struct Config { std::string base_url; // https://psycho-key.com std::string app; // product slug std::string api_secret; // 64 hex chars std::string version; // client version (verified if enforce_version is on) std::string tls_pin; // optional SHA-256 of server certificate DER (hex) bool anti_debug = false; bool require_v2 = true; // reject legacy v1 CBC responses }; struct License { long long id = 0; std::string status; int duration_days = 0; int duration_seconds = 0; int max_hwids = 0; std::string activated_at; std::string expires_at; int days_left = -1; long long seconds_left = -1; bool lifetime = false; }; struct Result { bool ok = false; std::string code; std::string message; std::string token; int retry_after = 0; std::string latest_version; std::string download_url; std::map variables; License license; }; namespace detail { /* ----------------------------- SHA-256 ----------------------------- */ class Sha256 { public: Sha256() { reset(); } void update(const void* data, size_t len) { const uint8_t* p = static_cast(data); total_ += len; while (len > 0) { size_t take = 64 - buflen_; if (take > len) take = len; std::memcpy(buf_ + buflen_, p, take); buflen_ += take; p += take; len -= take; if (buflen_ == 64) { transform(buf_); buflen_ = 0; } } } void update(const std::string& s) { update(s.data(), s.size()); } std::vector final() { uint64_t bits = total_ * 8; uint8_t pad = 0x80; update(&pad, 1); uint8_t zero = 0; while (buflen_ != 56) update(&zero, 1); uint8_t lenbuf[8]; for (int i = 0; i < 8; i++) lenbuf[i] = static_cast(bits >> (56 - 8 * i)); update(lenbuf, 8); std::vector out(32); for (int i = 0; i < 8; i++) { out[i * 4 + 0] = static_cast(h_[i] >> 24); out[i * 4 + 1] = static_cast(h_[i] >> 16); out[i * 4 + 2] = static_cast(h_[i] >> 8); out[i * 4 + 3] = static_cast(h_[i]); } return out; } static std::string hex(const std::vector& v) { static const char* d = "0123456789abcdef"; std::string out; out.reserve(v.size() * 2); for (uint8_t b : v) { out.push_back(d[b >> 4]); out.push_back(d[b & 0xF]); } return out; } private: void reset() { h_[0] = 0x6a09e667; h_[1] = 0xbb67ae85; h_[2] = 0x3c6ef372; h_[3] = 0xa54ff53a; h_[4] = 0x510e527f; h_[5] = 0x9b05688c; h_[6] = 0x1f83d9ab; h_[7] = 0x5be0cd19; total_ = 0; buflen_ = 0; } static uint32_t rotr(uint32_t x, int n) { return (x >> n) | (x << (32 - n)); } void transform(const uint8_t* chunk) { static const uint32_t K[64] = { 0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5, 0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174, 0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da, 0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967, 0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85, 0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070, 0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3, 0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2 }; uint32_t w[64]; for (int i = 0; i < 16; i++) { w[i] = (uint32_t(chunk[i * 4]) << 24) | (uint32_t(chunk[i * 4 + 1]) << 16) | (uint32_t(chunk[i * 4 + 2]) << 8) | uint32_t(chunk[i * 4 + 3]); } for (int i = 16; i < 64; i++) { uint32_t s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >> 3); uint32_t s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >> 10); w[i] = w[i - 16] + s0 + w[i - 7] + s1; } uint32_t a = h_[0], b = h_[1], c = h_[2], d = h_[3]; uint32_t e = h_[4], f = h_[5], g = h_[6], h = h_[7]; for (int i = 0; i < 64; i++) { uint32_t S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25); uint32_t ch = (e & f) ^ (~e & g); uint32_t t1 = h + S1 + ch + K[i] + w[i]; uint32_t S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22); uint32_t maj = (a & b) ^ (a & c) ^ (b & c); uint32_t t2 = S0 + maj; h = g; g = f; f = e; e = d + t1; d = c; c = b; b = a; a = t1 + t2; } h_[0] += a; h_[1] += b; h_[2] += c; h_[3] += d; h_[4] += e; h_[5] += f; h_[6] += g; h_[7] += h; } uint32_t h_[8]; uint64_t total_; uint8_t buf_[64]; size_t buflen_; }; inline std::vector sha256(const std::string& data) { Sha256 s; s.update(data); return s.final(); } inline std::string sha256_hex(const std::string& data) { return Sha256::hex(sha256(data)); } /* ----------------------------- HMAC ----------------------------- */ inline std::vector hmac_sha256(const std::vector& key, const std::string& msg) { std::vector k = key; if (k.size() > 64) k = sha256(std::string(k.begin(), k.end())); k.resize(64, 0); std::string inner; inner.reserve(64 + msg.size()); for (int i = 0; i < 64; i++) inner.push_back(static_cast(k[i] ^ 0x36)); inner += msg; std::vector innerHash = sha256(inner); std::string outer; outer.reserve(64 + 32); for (int i = 0; i < 64; i++) outer.push_back(static_cast(k[i] ^ 0x5c)); outer.append(reinterpret_cast(innerHash.data()), innerHash.size()); return sha256(outer); } inline std::string hmac_hex(const std::vector& key, const std::string& msg) { return Sha256::hex(hmac_sha256(key, msg)); } /* ----------------------------- HKDF ----------------------------- */ inline std::vector hkdf_sha256(const std::vector& ikm, const std::string& salt, const std::string& info, size_t length = 32) { std::vector saltVec(salt.begin(), salt.end()); std::vector prk = hmac_sha256(saltVec, std::string(ikm.begin(), ikm.end())); std::string t; std::vector out; uint8_t counter = 1; while (out.size() < length) { std::string block = t + info; block.push_back(static_cast(counter)); t = std::string(reinterpret_cast(hmac_sha256(prk, block).data()), 32); out.insert(out.end(), t.begin(), t.end()); counter++; } out.resize(length); return out; } /* ----------------------------- Base64 ----------------------------- */ inline std::string b64encode(const std::vector& data) { static const char* tbl = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; std::string out; size_t i = 0; while (i + 2 < data.size()) { uint32_t v = (data[i] << 16) | (data[i + 1] << 8) | data[i + 2]; out.push_back(tbl[(v >> 18) & 63]); out.push_back(tbl[(v >> 12) & 63]); out.push_back(tbl[(v >> 6) & 63]); out.push_back(tbl[v & 63]); i += 3; } if (i < data.size()) { uint32_t v = data[i] << 16; bool two = i + 1 < data.size(); if (two) v |= data[i + 1] << 8; out.push_back(tbl[(v >> 18) & 63]); out.push_back(tbl[(v >> 12) & 63]); out.push_back(two ? tbl[(v >> 6) & 63] : '='); out.push_back('='); } return out; } inline std::vector b64decode(const std::string& s) { auto val = [](char c) -> int { if (c >= 'A' && c <= 'Z') return c - 'A'; if (c >= 'a' && c <= 'z') return c - 'a' + 26; if (c >= '0' && c <= '9') return c - '0' + 52; if (c == '+' || c == '-') return 62; if (c == '/' || c == '_') return 63; return -1; }; std::vector out; int buffer = 0, bits = 0; for (char c : s) { if (c == '=') break; int v = val(c); if (v < 0) continue; buffer = (buffer << 6) | v; bits += 6; if (bits >= 8) { bits -= 8; out.push_back(static_cast((buffer >> bits) & 0xFF)); } } return out; } inline std::string hex_encode(const std::vector& v) { return Sha256::hex(v); } inline std::vector hex_decode(const std::string& s) { std::vector out; if (s.size() % 2) return out; auto nib = [](char c) -> int { if (c >= '0' && c <= '9') return c - '0'; if (c >= 'a' && c <= 'f') return c - 'a' + 10; if (c >= 'A' && c <= 'F') return c - 'A' + 10; return -1; }; for (size_t i = 0; i < s.size(); i += 2) { int hi = nib(s[i]), lo = nib(s[i + 1]); if (hi < 0 || lo < 0) return {}; out.push_back(static_cast((hi << 4) | lo)); } return out; } /* ----------------------------- AES-256-CBC ----------------------------- */ inline bool aes256cbc_decrypt(const std::vector& key, const std::vector& iv, const std::vector& ciphertext, std::vector& out) { if (key.size() != 32 || iv.size() != 16 || ciphertext.empty() || ciphertext.size() % 16 != 0) { return false; } BCRYPT_ALG_HANDLE alg = nullptr; BCRYPT_KEY_HANDLE keyHandle = nullptr; bool ok = false; if (BCryptOpenAlgorithmProvider(&alg, BCRYPT_AES_ALGORITHM, nullptr, 0) != 0) { return false; } BCryptSetProperty(alg, BCRYPT_CHAINING_MODE, reinterpret_cast(const_cast(BCRYPT_CHAIN_MODE_CBC)), sizeof(BCRYPT_CHAIN_MODE_CBC), 0); DWORD objectLength = 0, result = 0; BCryptGetProperty(alg, BCRYPT_OBJECT_LENGTH, reinterpret_cast(&objectLength), sizeof(objectLength), &result, 0); std::vector keyObject(objectLength); if (BCryptGenerateSymmetricKey(alg, &keyHandle, keyObject.data(), objectLength, const_cast(key.data()), static_cast(key.size()), 0) == 0) { std::vector buffer(ciphertext.size() + 16); ULONG written = 0; if (BCryptDecrypt(keyHandle, const_cast(ciphertext.data()), static_cast(ciphertext.size()), nullptr, const_cast(iv.data()), static_cast(iv.size()), buffer.data(), static_cast(buffer.size()), &written, BCRYPT_BLOCK_PADDING) == 0) { buffer.resize(written); out = std::move(buffer); ok = true; } } if (keyHandle) BCryptDestroyKey(keyHandle); BCryptCloseAlgorithmProvider(alg, 0); return ok; } /* ----------------------------- AES-256-GCM ----------------------------- */ inline bool aes256gcm_encrypt(const std::vector& key, const std::vector& iv, const std::string& plaintext, const std::string& aad, std::vector& ciphertext, std::vector& tag) { if (key.size() != 32 || iv.size() != 12) return false; BCRYPT_ALG_HANDLE alg = nullptr; BCRYPT_KEY_HANDLE keyHandle = nullptr; bool ok = false; if (BCryptOpenAlgorithmProvider(&alg, BCRYPT_AES_ALGORITHM, nullptr, 0) != 0) { return false; } BCryptSetProperty(alg, BCRYPT_CHAINING_MODE, reinterpret_cast(const_cast(BCRYPT_CHAIN_MODE_GCM)), sizeof(BCRYPT_CHAIN_MODE_GCM), 0); DWORD objectLength = 0, result = 0; BCryptGetProperty(alg, BCRYPT_OBJECT_LENGTH, reinterpret_cast(&objectLength), sizeof(objectLength), &result, 0); std::vector keyObject(objectLength); if (BCryptGenerateSymmetricKey(alg, &keyHandle, keyObject.data(), objectLength, const_cast(key.data()), static_cast(key.size()), 0) == 0) { ciphertext.resize(plaintext.size()); tag.resize(16); BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO info; BCRYPT_INIT_AUTH_MODE_INFO(info); info.pbNonce = const_cast(iv.data()); info.cbNonce = static_cast(iv.size()); info.pbAuthData = aad.empty() ? nullptr : const_cast(reinterpret_cast(aad.data())); info.cbAuthData = static_cast(aad.size()); info.pbTag = tag.data(); info.cbTag = static_cast(tag.size()); ULONG written = 0; if (BCryptEncrypt(keyHandle, const_cast(reinterpret_cast(plaintext.data())), static_cast(plaintext.size()), &info, nullptr, 0, ciphertext.data(), static_cast(ciphertext.size()), &written, 0) == 0) { ciphertext.resize(written); ok = true; } } if (keyHandle) BCryptDestroyKey(keyHandle); BCryptCloseAlgorithmProvider(alg, 0); return ok; } inline bool aes256gcm_decrypt(const std::vector& key, const std::vector& iv, const std::vector& ciphertext, const std::vector& tag, const std::string& aad, std::vector& out) { if (key.size() != 32 || iv.size() != 12 || tag.size() != 16) return false; BCRYPT_ALG_HANDLE alg = nullptr; BCRYPT_KEY_HANDLE keyHandle = nullptr; bool ok = false; if (BCryptOpenAlgorithmProvider(&alg, BCRYPT_AES_ALGORITHM, nullptr, 0) != 0) { return false; } BCryptSetProperty(alg, BCRYPT_CHAINING_MODE, reinterpret_cast(const_cast(BCRYPT_CHAIN_MODE_GCM)), sizeof(BCRYPT_CHAIN_MODE_GCM), 0); DWORD objectLength = 0, result = 0; BCryptGetProperty(alg, BCRYPT_OBJECT_LENGTH, reinterpret_cast(&objectLength), sizeof(objectLength), &result, 0); std::vector keyObject(objectLength); if (BCryptGenerateSymmetricKey(alg, &keyHandle, keyObject.data(), objectLength, const_cast(key.data()), static_cast(key.size()), 0) == 0) { out.resize(ciphertext.size()); BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO info; BCRYPT_INIT_AUTH_MODE_INFO(info); info.pbNonce = const_cast(iv.data()); info.cbNonce = static_cast(iv.size()); info.pbAuthData = aad.empty() ? nullptr : const_cast(reinterpret_cast(aad.data())); info.cbAuthData = static_cast(aad.size()); info.pbTag = const_cast(tag.data()); info.cbTag = static_cast(tag.size()); ULONG written = 0; if (BCryptDecrypt(keyHandle, const_cast(ciphertext.data()), static_cast(ciphertext.size()), &info, nullptr, 0, out.data(), static_cast(out.size()), &written, 0) == 0) { out.resize(written); ok = true; } } if (keyHandle) BCryptDestroyKey(keyHandle); BCryptCloseAlgorithmProvider(alg, 0); return ok; } /* ----------------------------- random ----------------------------- */ inline std::vector random_bytes(size_t count) { std::vector buf(count); if (BCryptGenRandom(nullptr, buf.data(), static_cast(buf.size()), BCRYPT_USE_SYSTEM_PREFERRED_RNG) != 0) { for (auto& b : buf) b = static_cast(rand() & 0xFF); } return buf; } inline std::string random_hex(size_t bytes) { return hex_encode(random_bytes(bytes)); } /* ----------------------------- JSON ----------------------------- */ struct Json { enum class Type { Null, Bool, Number, String, Array, Object }; Type type = Type::Null; bool boolean = false; double number = 0; std::string text; std::vector array; std::map object; const Json* get(const std::string& key) const { auto it = object.find(key); return it == object.end() ? nullptr : &it->second; } std::string str(const std::string& key, const std::string& def = "") const { const Json* v = get(key); return (v && v->type == Type::String) ? v->text : def; } double num(const std::string& key, double def = 0) const { const Json* v = get(key); return (v && v->type == Type::Number) ? v->number : def; } bool flag(const std::string& key, bool def = false) const { const Json* v = get(key); return (v && v->type == Type::Bool) ? v->boolean : def; } bool has(const std::string& key) const { return object.count(key) > 0; } }; class JsonParser { public: explicit JsonParser(const std::string& s) : s_(s) {} bool parse(Json& out) { skip(); if (!parse_value(out)) return false; skip(); return pos_ == s_.size(); } private: void skip() { while (pos_ < s_.size()) { char c = s_[pos_]; if (c == ' ' || c == '\t' || c == '\n' || c == '\r') pos_++; else break; } } bool parse_value(Json& out) { skip(); if (pos_ >= s_.size()) return false; char c = s_[pos_]; if (c == '{') return parse_object(out); if (c == '[') return parse_array(out); if (c == '"') { out.type = Json::Type::String; return parse_string(out.text); } if (c == 't') { if (s_.compare(pos_, 4, "true") == 0) { pos_ += 4; out.type = Json::Type::Bool; out.boolean = true; return true; } return false; } if (c == 'f') { if (s_.compare(pos_, 5, "false") == 0) { pos_ += 5; out.type = Json::Type::Bool; out.boolean = false; return true; } return false; } if (c == 'n') { if (s_.compare(pos_, 4, "null") == 0) { pos_ += 4; out.type = Json::Type::Null; return true; } return false; } return parse_number(out); } bool parse_object(Json& out) { out.type = Json::Type::Object; pos_++; // { skip(); if (pos_ < s_.size() && s_[pos_] == '}') { pos_++; return true; } while (pos_ < s_.size()) { skip(); std::string key; if (!parse_string(key)) return false; skip(); if (pos_ >= s_.size() || s_[pos_] != ':') return false; pos_++; Json value; if (!parse_value(value)) return false; out.object[key] = std::move(value); skip(); if (pos_ >= s_.size()) return false; if (s_[pos_] == ',') { pos_++; continue; } if (s_[pos_] == '}') { pos_++; return true; } return false; } return false; } bool parse_array(Json& out) { out.type = Json::Type::Array; pos_++; // [ skip(); if (pos_ < s_.size() && s_[pos_] == ']') { pos_++; return true; } while (pos_ < s_.size()) { Json value; if (!parse_value(value)) return false; out.array.push_back(std::move(value)); skip(); if (pos_ >= s_.size()) return false; if (s_[pos_] == ',') { pos_++; continue; } if (s_[pos_] == ']') { pos_++; return true; } return false; } return false; } bool parse_string(std::string& out) { if (pos_ >= s_.size() || s_[pos_] != '"') return false; pos_++; out.clear(); while (pos_ < s_.size()) { unsigned char c = static_cast(s_[pos_++]); if (c == '"') return true; if (c == '\\') { if (pos_ >= s_.size()) return false; char e = s_[pos_++]; switch (e) { case '"': out.push_back('"'); break; case '\\': out.push_back('\\'); break; case '/': out.push_back('/'); break; case 'b': out.push_back('\b'); break; case 'f': out.push_back('\f'); break; case 'n': out.push_back('\n'); break; case 'r': out.push_back('\r'); break; case 't': out.push_back('\t'); break; case 'u': { if (pos_ + 4 > s_.size()) return false; unsigned cp = std::stoul(s_.substr(pos_, 4), nullptr, 16); pos_ += 4; if (cp >= 0xD800 && cp <= 0xDBFF && pos_ + 6 <= s_.size() && s_[pos_] == '\\' && s_[pos_ + 1] == 'u') { unsigned low = std::stoul(s_.substr(pos_ + 2, 4), nullptr, 16); pos_ += 6; cp = 0x10000 + ((cp - 0xD800) << 10) + (low - 0xDC00); } if (cp <= 0x7F) out.push_back(static_cast(cp)); else if (cp <= 0x7FF) { out.push_back(static_cast(0xC0 | (cp >> 6))); out.push_back(static_cast(0x80 | (cp & 0x3F))); } else if (cp <= 0xFFFF) { out.push_back(static_cast(0xE0 | (cp >> 12))); out.push_back(static_cast(0x80 | ((cp >> 6) & 0x3F))); out.push_back(static_cast(0x80 | (cp & 0x3F))); } else { out.push_back(static_cast(0xF0 | (cp >> 18))); out.push_back(static_cast(0x80 | ((cp >> 12) & 0x3F))); out.push_back(static_cast(0x80 | ((cp >> 6) & 0x3F))); out.push_back(static_cast(0x80 | (cp & 0x3F))); } break; } default: return false; } } else { out.push_back(static_cast(c)); } } return false; } bool parse_number(Json& out) { size_t start = pos_; if (pos_ < s_.size() && (s_[pos_] == '-' || s_[pos_] == '+')) pos_++; while (pos_ < s_.size() && ((s_[pos_] >= '0' && s_[pos_] <= '9') || s_[pos_] == '.' || s_[pos_] == 'e' || s_[pos_] == 'E' || s_[pos_] == '-' || s_[pos_] == '+')) { pos_++; } if (start == pos_) return false; try { out.type = Json::Type::Number; out.number = std::stod(s_.substr(start, pos_ - start)); return true; } catch (...) { return false; } } const std::string& s_; size_t pos_ = 0; }; inline std::string json_escape(const std::string& in) { std::string out; out.reserve(in.size() + 8); for (unsigned char c : in) { switch (c) { case '"': out += "\\\""; break; case '\\': out += "\\\\"; break; case '\b': out += "\\b"; break; case '\f': out += "\\f"; break; case '\n': out += "\\n"; break; case '\r': out += "\\r"; break; case '\t': out += "\\t"; break; default: if (c < 0x20) { char buf[8]; std::snprintf(buf, sizeof(buf), "\\u%04x", c); out += buf; } else { out.push_back(static_cast(c)); } } } return out; } /* ----------------------------- WinHTTP ----------------------------- */ inline std::wstring utf8_to_wide(const std::string& s) { if (s.empty()) return L""; int len = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), static_cast(s.size()), nullptr, 0); std::wstring out(len, L'\0'); MultiByteToWideChar(CP_UTF8, 0, s.c_str(), static_cast(s.size()), out.data(), len); return out; } inline std::string wide_to_utf8(const std::wstring& s) { if (s.empty()) return ""; int len = WideCharToMultiByte(CP_UTF8, 0, s.c_str(), static_cast(s.size()), nullptr, 0, nullptr, nullptr); std::string out(len, '\0'); WideCharToMultiByte(CP_UTF8, 0, s.c_str(), static_cast(s.size()), out.data(), len, nullptr, nullptr); return out; } struct HttpResponse { bool transportOk = false; int status = 0; std::string body; }; inline HttpResponse http_post(const std::string& url, const std::string& body, const std::string& tlsPin) { HttpResponse result; std::wstring wurl = utf8_to_wide(url); URL_COMPONENTS uc{}; uc.dwStructSize = sizeof(uc); wchar_t host[512] = {}; wchar_t path[4096] = {}; uc.lpszHostName = host; uc.dwHostNameLength = 512; uc.lpszUrlPath = path; uc.dwUrlPathLength = 4096; if (!WinHttpCrackUrl(wurl.c_str(), 0, 0, &uc)) { return result; } bool secure = uc.nScheme == INTERNET_SCHEME_HTTPS; HINTERNET session = WinHttpOpen(L"PsychoKey/1.0", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); if (!session) return result; WinHttpSetTimeouts(session, 5000, 5000, 5000, 10000); DWORD secureProtocols = WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2; #ifdef WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_3 secureProtocols |= WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_3; #endif WinHttpSetOption(session, WINHTTP_OPTION_SECURE_PROTOCOLS, &secureProtocols, sizeof(secureProtocols)); HINTERNET connection = WinHttpConnect(session, host, uc.nPort, 0); if (!connection) { WinHttpCloseHandle(session); return result; } std::wstring target = path[0] ? std::wstring(path) : L"/"; HINTERNET request = WinHttpOpenRequest(connection, L"POST", target.c_str(), nullptr, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, secure ? WINHTTP_FLAG_SECURE : 0); if (!request) { WinHttpCloseHandle(connection); WinHttpCloseHandle(session); return result; } const wchar_t* headers = L"Content-Type: application/json\r\n"; BOOL sent = WinHttpSendRequest(request, headers, static_cast(-1), const_cast(body.data()), static_cast(body.size()), static_cast(body.size()), 0); if (sent && WinHttpReceiveResponse(request, nullptr)) { bool pinOk = true; if (!tlsPin.empty()) { CERT_CONTEXT* cert = nullptr; DWORD certSize = sizeof(cert); if (WinHttpQueryOption(request, WINHTTP_OPTION_SERVER_CERT_CONTEXT, &cert, &certSize) && cert) { std::string der(reinterpret_cast(cert->pbCertEncoded), cert->cbCertEncoded); std::string actual = Sha256::hex(sha256(der)); CertFreeCertificateContext(cert); std::string expected; expected.reserve(tlsPin.size()); for (char c : tlsPin) { if (c != ':' && c != ' ') expected.push_back(static_cast(std::tolower(static_cast(c)))); } pinOk = expected == actual; } else { pinOk = false; } } if (!pinOk) { result.status = -1; WinHttpCloseHandle(request); WinHttpCloseHandle(connection); WinHttpCloseHandle(session); return result; } DWORD statusCode = 0, size = sizeof(statusCode); WinHttpQueryHeaders(request, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, WINHTTP_HEADER_NAME_BY_INDEX, &statusCode, &size, WINHTTP_NO_HEADER_INDEX); result.status = static_cast(statusCode); DWORD available = 0; do { available = 0; if (!WinHttpQueryDataAvailable(request, &available) || available == 0) break; std::vector buffer(available); DWORD read = 0; if (!WinHttpReadData(request, buffer.data(), available, &read)) break; result.body.append(buffer.data(), read); } while (available > 0); result.transportOk = true; } WinHttpCloseHandle(request); WinHttpCloseHandle(connection); WinHttpCloseHandle(session); return result; } /* ----------------------------- HWID ----------------------------- */ inline std::string wide_reg_value(HKEY root, const wchar_t* subkey, const wchar_t* name) { HKEY key = nullptr; if (RegOpenKeyExW(root, subkey, 0, KEY_READ | KEY_WOW64_64KEY, &key) != ERROR_SUCCESS) { return ""; } wchar_t buffer[512] = {}; DWORD size = sizeof(buffer); DWORD type = 0; std::string out; if (RegQueryValueExW(key, name, nullptr, &type, reinterpret_cast(buffer), &size) == ERROR_SUCCESS && (type == REG_SZ || type == REG_EXPAND_SZ)) { out = wide_to_utf8(buffer); } RegCloseKey(key); return out; } inline std::string smbios_system_uuid(); inline std::string smbios_baseboard_serial(); inline std::string disk_serial(); inline std::string cpu_fingerprint(); inline std::string compute_hwid() { std::string uuid = smbios_system_uuid(); std::string board = smbios_baseboard_serial(); std::string disk = disk_serial(); std::string cpu = cpu_fingerprint(); std::string material; material += "uuid=" + uuid; material += "|board=" + board; material += "|disk=" + disk; material += "|cpu=" + cpu; // Hardware signals survive OS reinstall / format. If none are readable // (locked-down VM, restricted permissions), fall back to OS identifiers. if (uuid.empty() && board.empty() && disk.empty()) { std::string machineGuid = wide_reg_value(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Cryptography", L"MachineGuid"); wchar_t volumeName[256] = {}; DWORD volumeSerial = 0; GetVolumeInformationW(L"C:\\", volumeName, 256, &volumeSerial, nullptr, nullptr, nullptr, 0); char serialHex[16]; std::snprintf(serialHex, sizeof(serialHex), "%08lX", static_cast(volumeSerial)); material += "|guid=" + machineGuid; material += "|vol=" + std::string(serialHex); } return sha256_hex(material); } /* ----------------------------- Hardware fingerprint parts ----------------------------- */ inline std::string smbios_string(const uint8_t* structure, uint8_t length, uint8_t index) { if (index == 0) return ""; const uint8_t* p = structure + length; uint8_t current = 1; for (int guard = 0; guard < 64; guard++) { if (*p == 0) return ""; std::string s(reinterpret_cast(p)); if (current == index) return s; p += s.size() + 1; current++; } return ""; } inline constexpr DWORD firmware_signature() { return static_cast('R') | (static_cast('S') << 8) | (static_cast('M') << 16) | (static_cast('B') << 24); } inline const uint8_t* smbios_table(std::vector& buffer, uint32_t& tableLength) { tableLength = 0; DWORD size = GetSystemFirmwareTable(firmware_signature(), 0, nullptr, 0); if (size < 8) return nullptr; buffer.resize(size); if (!GetSystemFirmwareTable(firmware_signature(), 0, buffer.data(), size)) return nullptr; tableLength = *reinterpret_cast(buffer.data() + 4); if (tableLength == 0 || tableLength > buffer.size() - 8) return nullptr; return buffer.data() + 8; } inline std::string smbios_system_uuid() { std::vector buffer; uint32_t length = 0; const uint8_t* table = smbios_table(buffer, length); if (!table) return ""; const uint8_t* end = table + length; const uint8_t* p = table; while (p + 4 <= end) { uint8_t type = p[0]; uint8_t len = p[1]; if (len < 4) break; if (type == 1 && len >= 0x19) { const uint8_t* u = p + 8; char out[40]; std::snprintf(out, sizeof(out), "%02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X", u[3], u[2], u[1], u[0], u[5], u[4], u[7], u[6], u[8], u[9], u[10], u[11], u[12], u[13], u[14], u[15]); return out; } const uint8_t* q = p + len; if (q + 2 > end) break; while (q + 1 < end && !(q[0] == 0 && q[1] == 0)) q++; p = q + 2; } return ""; } inline std::string smbios_baseboard_serial() { std::vector buffer; uint32_t length = 0; const uint8_t* table = smbios_table(buffer, length); if (!table) return ""; const uint8_t* end = table + length; const uint8_t* p = table; while (p + 4 <= end) { uint8_t type = p[0]; uint8_t len = p[1]; if (len < 4) break; if (type == 2 && len >= 8) { return smbios_string(p, len, p[7]); } const uint8_t* q = p + len; if (q + 2 > end) break; while (q + 1 < end && !(q[0] == 0 && q[1] == 0)) q++; p = q + 2; } return ""; } inline std::string disk_serial() { HANDLE handle = CreateFileW(L"\\\\.\\PhysicalDrive0", 0, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr); if (handle == INVALID_HANDLE_VALUE) return ""; STORAGE_PROPERTY_QUERY query{}; query.PropertyId = StorageDeviceProperty; query.QueryType = PropertyStandardQuery; std::vector output(4096); DWORD returned = 0; std::string serial; if (DeviceIoControl(handle, IOCTL_STORAGE_QUERY_PROPERTY, &query, sizeof(query), output.data(), static_cast(output.size()), &returned, nullptr)) { auto* descriptor = reinterpret_cast(output.data()); if (descriptor->SerialNumberOffset > 0 && descriptor->SerialNumberOffset < returned && descriptor->SerialNumberOffset < output.size()) { serial = reinterpret_cast(output.data() + descriptor->SerialNumberOffset); while (!serial.empty() && (serial.back() == ' ' || serial.back() == '\0')) serial.pop_back(); } } CloseHandle(handle); return serial; } inline std::string cpu_fingerprint() { int regs[4] = {}; __cpuid(regs, 0); char vendor[13] = {}; std::memcpy(vendor, ®s[1], 4); std::memcpy(vendor + 4, ®s[3], 4); std::memcpy(vendor + 8, ®s[2], 4); char brand[49] = {}; for (int i = 0; i < 3; i++) { __cpuid(regs, 0x80000002 + i); std::memcpy(brand + i * 16, regs, 16); } __cpuid(regs, 1); char signature[16]; std::snprintf(signature, sizeof(signature), "%08X", static_cast(regs[0])); return std::string(vendor) + "|" + brand + "|" + signature; } } // namespace detail /* ----------------------------- anti-debug ----------------------------- */ namespace security { inline bool debugger_detected() { if (IsDebuggerPresent()) { return true; } BOOL remote = FALSE; if (CheckRemoteDebuggerPresent(GetCurrentProcess(), &remote) && remote) { return true; } using NtQueryInformationProcessFn = LONG (NTAPI*)(HANDLE, ULONG, PVOID, ULONG, PULONG); HMODULE ntdll = GetModuleHandleW(L"ntdll.dll"); if (ntdll) { auto query = reinterpret_cast( reinterpret_cast(GetProcAddress(ntdll, "NtQueryInformationProcess"))); if (query) { ULONG_PTR debugPort = 0; ULONG returned = 0; if (query(GetCurrentProcess(), 7, &debugPort, sizeof(debugPort), &returned) == 0 && debugPort != 0) { return true; } ULONG flags = 0; if (query(GetCurrentProcess(), 0x1F, &flags, sizeof(flags), &returned) == 0 && (flags & 1)) { return true; } HANDLE debugObject = nullptr; if (query(GetCurrentProcess(), 0x1E, &debugObject, sizeof(debugObject), &returned) == 0 && debugObject != nullptr) { return true; } } } return false; } inline void guard() { if (debugger_detected()) { ExitProcess(0); } } } // namespace security /* ----------------------------- string obfuscation ----------------------------- */ namespace detail { template class ObfString { public: constexpr ObfString(const char (&s)[N]) : data_{} { for (size_t i = 0; i < N; ++i) { data_[i] = static_cast(static_cast(s[i]) ^ key(i)); } } std::string decode() const { std::string out(N > 0 ? N - 1 : 0, '\0'); for (size_t i = 0; i + 1 < N; ++i) { out[i] = static_cast(static_cast(data_[i]) ^ key(i)); } return out; } private: static constexpr uint8_t key(size_t i) { return static_cast( ((Seed >> ((i % 4) * 8)) & 0xFF) ^ static_cast((i * 131u + 77u) & 0xFF) ); } char data_[N]; }; } // namespace detail // PK_OBF("literal") — compile-time obfuscated string, decoded at runtime. #define PK_OBF(s) (::psycho::detail::ObfString(__LINE__ * 2654435761u)>(s).decode()) /* ----------------------------- Client ----------------------------- */ class Client { public: explicit Client(Config config) : config_(std::move(config)), hwid_(detail::compute_hwid()) { while (!config_.base_url.empty() && config_.base_url.back() == '/') { config_.base_url.pop_back(); } } Result init() { Result res = request("init", ""); if (res.ok) { for (const auto& kv : res.variables) vars_[kv.first] = kv.second; } return res; } Result auth(const std::string& license_key) { Result res = request("license", license_key); if (res.ok && !res.token.empty()) { token_ = res.token; for (const auto& kv : res.variables) vars_[kv.first] = kv.second; } else { token_.clear(); } return res; } Result heartbeat() { Result res = request("heartbeat", ""); if (res.ok && !res.token.empty()) { token_ = res.token; for (const auto& kv : res.variables) vars_[kv.first] = kv.second; } else if (!res.ok) { token_.clear(); } return res; } void logout() { if (!token_.empty()) { request("logout", ""); } token_.clear(); vars_.clear(); } // Self-service HWID reset (after format / hardware change). // Subject to the product's allow_hwid_reset + cooldown policy. Result reset_hwid(const std::string& license_key) { Result res = request("reset", license_key); if (res.ok && !res.token.empty()) { token_ = res.token; for (const auto& kv : res.variables) vars_[kv.first] = kv.second; } return res; } bool authenticated() const { return !token_.empty(); } const std::string& hwid() const { return hwid_; } const std::string& token() const { return token_; } const Config& config() const { return config_; } std::string var(const std::string& key, const std::string& def = "") const { auto it = vars_.find(key); return it == vars_.end() ? def : it->second; } private: Result request(const std::string& action, const std::string& license_key) { Result out; if (config_.anti_debug && security::debugger_detected()) { out.code = "DEBUGGER"; out.message = "A debugger was detected."; return out; } const bool isLocal = config_.base_url.rfind("http://127.0.0.1", 0) == 0 || config_.base_url.rfind("http://localhost", 0) == 0; if (config_.base_url.rfind("https://", 0) != 0 && !isLocal) { out.code = "HTTPS_REQUIRED"; out.message = "Refusing to send credentials over plain HTTP."; return out; } std::vector secret = detail::hex_decode(config_.api_secret); if (secret.size() != 32 || config_.app.empty()) { out.code = "CLIENT_CONFIG"; out.message = "Invalid product secret (64 hex chars) or app slug."; return out; } std::string nonce = detail::random_hex(16); long long ts = static_cast(std::time(nullptr)); std::string canonical = config_.app + "|" + action + "|" + nonce + "|" + std::to_string(ts) + "|" + hwid_ + "|" + license_key + "|" + token_; std::string signature = detail::hmac_hex(secret, canonical); std::string inner; inner.reserve(512); inner += "{\"action\":\"" + detail::json_escape(action) + "\""; inner += ",\"nonce\":\"" + nonce + "\""; inner += ",\"ts\":" + std::to_string(ts); inner += ",\"hwid\":\"" + detail::json_escape(hwid_) + "\""; inner += ",\"license_key\":\"" + detail::json_escape(license_key) + "\""; inner += ",\"token\":\"" + detail::json_escape(token_) + "\""; inner += ",\"version\":\"" + detail::json_escape(config_.version) + "\""; inner += ",\"sig\":\"" + signature + "\"}"; std::vector reqKey = detail::hkdf_sha256(secret, "psychokey-salt-v1", "psychokey-req-v2|" + config_.app, 32); std::vector reqIv = detail::random_bytes(12); std::vector reqCt, reqTag; if (!detail::aes256gcm_encrypt(reqKey, reqIv, inner, config_.app, reqCt, reqTag)) { out.code = "CLIENT_CRYPTO"; out.message = "Request encryption failed."; return out; } std::string body; body.reserve(512); body += "{\"app\":\"" + detail::json_escape(config_.app) + "\""; body += ",\"v\":2"; body += ",\"iv\":\"" + detail::b64encode(reqIv) + "\""; body += ",\"ct\":\"" + detail::b64encode(reqCt) + "\""; body += ",\"tag\":\"" + detail::b64encode(reqTag) + "\"}"; detail::HttpResponse http = detail::http_post(config_.base_url + "/api/v1.php", body, config_.tls_pin); if (!http.transportOk) { out.code = "NETWORK"; out.message = "Could not reach the license server."; return out; } detail::Json root; detail::JsonParser parser(http.body); if (!parser.parse(root)) { out.code = "CLIENT_PARSE"; out.message = "Malformed server response."; return out; } detail::Json payload; bool encrypted = false; if (static_cast(root.num("v", 0)) == 2) { encrypted = true; std::vector iv = detail::b64decode(root.str("iv")); std::vector ciphertext = detail::b64decode(root.str("ct")); std::vector tag = detail::b64decode(root.str("tag")); std::vector respKey = detail::hkdf_sha256(secret, "psychokey-salt-v1", "psychokey-resp-v2|" + config_.app, 32); std::string aad = config_.app + "|" + action + "|" + nonce; std::vector plain; if (!detail::aes256gcm_decrypt(respKey, iv, ciphertext, tag, aad, plain)) { out.code = "CLIENT_INTEGRITY"; out.message = "Response authentication failed."; return out; } std::string plainText(plain.begin(), plain.end()); detail::JsonParser innerParser(plainText); if (!innerParser.parse(payload)) { out.code = "CLIENT_PARSE"; out.message = "Malformed decrypted payload."; return out; } } else if (!config_.require_v2 && root.has("ct") && root.has("iv") && root.has("tag")) { encrypted = true; // Legacy v1 response support (only when require_v2 = false). std::vector iv = detail::b64decode(root.str("iv")); std::vector ciphertext = detail::b64decode(root.str("ct")); std::vector tag = detail::b64decode(root.str("tag")); std::vector encKey = detail::hkdf_sha256(secret, "psychokey-salt-v1", "psychokey-enc-v1|" + config_.app, 32); std::vector macKey = detail::hkdf_sha256(secret, "psychokey-salt-v1", "psychokey-mac-v1|" + config_.app, 32); std::string signedData(reinterpret_cast(iv.data()), iv.size()); signedData.append(reinterpret_cast(ciphertext.data()), ciphertext.size()); std::vector expected = detail::hmac_sha256(macKey, signedData); bool tagMatch = expected.size() == tag.size(); if (tagMatch) { unsigned char diff = 0; for (size_t i = 0; i < tag.size(); i++) { diff |= static_cast(expected[i] ^ tag[i]); } tagMatch = diff == 0; } if (!tagMatch) { out.code = "CLIENT_INTEGRITY"; out.message = "Response signature mismatch."; return out; } std::vector plain; if (!detail::aes256cbc_decrypt(encKey, iv, ciphertext, plain)) { out.code = "CLIENT_DECRYPT"; out.message = "Could not decrypt response."; return out; } std::string plainText(plain.begin(), plain.end()); detail::JsonParser innerParser(plainText); if (!innerParser.parse(payload)) { out.code = "CLIENT_PARSE"; out.message = "Malformed decrypted payload."; return out; } } else { // Failures may be plain JSON, but an unencrypted success response is // never trusted: it would allow a network attacker to strip crypto. if (root.flag("success", false)) { out.code = "CLIENT_INTEGRITY"; out.message = "Unencrypted success response rejected."; return out; } payload = root; } if (encrypted) { double respTs = payload.num("ts", 0); if (respTs > 0 && std::abs(respTs - static_cast(ts)) > 300.0) { out.code = "CLIENT_INTEGRITY"; out.message = "Response timestamp outside allowed window."; return out; } } out.ok = payload.flag("success", false); out.code = payload.str("code", out.ok ? "OK" : "ERROR"); out.message = payload.str("message", ""); out.retry_after = static_cast(payload.num("retry_after", 0)); out.latest_version = payload.str("latest_version", ""); out.download_url = payload.str("download_url", ""); const detail::Json* vars = payload.get("variables"); if (vars && vars->type == detail::Json::Type::Object) { for (const auto& kv : vars->object) { if (kv.second.type == detail::Json::Type::String) { out.variables[kv.first] = kv.second.text; } } } if (out.ok) { out.token = payload.str("token", ""); const detail::Json* lic = payload.get("license"); if (lic && lic->type == detail::Json::Type::Object) { out.license.id = static_cast(lic->num("id", 0)); out.license.status = lic->str("status"); out.license.duration_days = static_cast(lic->num("duration", 0)); out.license.duration_seconds = static_cast(lic->num("duration_seconds", 0)); out.license.max_hwids = static_cast(lic->num("max_hwids", 0)); out.license.activated_at = lic->str("activated_at"); out.license.expires_at = lic->str("expires_at"); out.license.days_left = static_cast(lic->num("days_left", -1)); out.license.seconds_left = static_cast(lic->num("seconds_left", -1)); out.license.lifetime = lic->flag("lifetime", false); } } return out; } Config config_; std::string hwid_; std::string token_; std::map vars_; }; } // namespace psycho #endif // PSYCHOKEY_HPP