// Psycho Key — Java SDK (v2 AES-256-GCM protocol) // Requires Java 11+ standard library only (zero external dependencies). // Build: javac PsychoKey.java ExampleJava.java && java ExampleJava import javax.crypto.Cipher; import javax.crypto.Mac; import javax.crypto.spec.GCMParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.security.MessageDigest; import java.security.SecureRandom; import java.time.Duration; import java.time.Instant; import java.util.Base64; import java.util.LinkedHashMap; import java.util.Map; public final class PsychoKey { public static final class Config { public String baseUrl = "https://psycho-key.com"; public String app = ""; public String apiSecret = ""; public String version = "1.0.0"; public boolean requireV2 = true; public Config(String app, String apiSecret) { this.app = app; this.apiSecret = apiSecret; } } public static final class License { public long id; public String status = ""; public int durationDays; public int durationSeconds; public int maxHwids; public String activatedAt = ""; public String expiresAt = ""; public int daysLeft = -1; public long secondsLeft = -1; public boolean lifetime; } public static final class Result { public boolean ok; public String code = ""; public String message = ""; public String token = ""; public int retryAfter; public String latestVersion = ""; public String downloadUrl = ""; public final Map variables = new LinkedHashMap<>(); public License license = new License(); } public static final class Client { private static final String HKDF_SALT = "psychokey-salt-v1"; private static final SecureRandom RNG = new SecureRandom(); private final Config config; private final byte[] secret; private final String hwid; private final HttpClient http; private final Map vars = new LinkedHashMap<>(); private String token = ""; public Client(Config config) { this.config = config; this.secret = hexDecode(config.apiSecret.trim()); if (this.secret.length != 32) { throw new IllegalArgumentException("apiSecret must be 64 hex chars (32 bytes)"); } this.hwid = detectHwid(); this.http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(15)).build(); } public String hwid() { return hwid; } public String var(String key) { return vars.getOrDefault(key, ""); } public Result init() { return call("init", ""); } public Result auth(String licenseKey) { Result r = call("license", licenseKey); if (r.ok && !r.token.isEmpty()) token = r.token; vars.putAll(r.variables); return r; } public Result heartbeat() { Result r = call("heartbeat", ""); if (r.ok && !r.token.isEmpty()) token = r.token; vars.putAll(r.variables); return r; } public Result logout() { Result r = call("logout", ""); token = ""; return r; } public Result resetHwid(String licenseKey) { Result r = call("reset", licenseKey); if (r.ok && !r.token.isEmpty()) token = r.token; vars.putAll(r.variables); return r; } private Result call(String action, String licenseKey) { Result out = new Result(); try { byte[] nonceBytes = new byte[16]; RNG.nextBytes(nonceBytes); String nonce = hexEncode(nonceBytes); long ts = Instant.now().getEpochSecond(); String canonical = String.join("|", config.app, action, nonce, Long.toString(ts), hwid, licenseKey, token); String sig = hexEncode(hmacSha256(secret, canonical.getBytes(StandardCharsets.UTF_8))); String inner = "{" + "\"action\":\"" + jsonEscape(action) + "\"" + ",\"nonce\":\"" + nonce + "\"" + ",\"ts\":" + ts + ",\"hwid\":\"" + jsonEscape(hwid) + "\"" + ",\"license_key\":\"" + jsonEscape(licenseKey) + "\"" + ",\"token\":\"" + jsonEscape(token) + "\"" + ",\"version\":\"" + jsonEscape(config.version) + "\"" + ",\"sig\":\"" + sig + "\"}"; byte[] reqKey = hkdfSha256(secret, HKDF_SALT, "psychokey-req-v2|" + config.app, 32); byte[] iv = new byte[12]; RNG.nextBytes(iv); Cipher enc = Cipher.getInstance("AES/GCM/NoPadding"); enc.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(reqKey, "AES"), new GCMParameterSpec(128, iv)); enc.updateAAD(config.app.getBytes(StandardCharsets.UTF_8)); byte[] sealed = enc.doFinal(inner.getBytes(StandardCharsets.UTF_8)); int split = sealed.length - 16; byte[] ct = new byte[split]; byte[] tag = new byte[16]; System.arraycopy(sealed, 0, ct, 0, split); System.arraycopy(sealed, split, tag, 0, 16); Base64.Encoder b64e = Base64.getEncoder(); String env = "{" + "\"app\":\"" + jsonEscape(config.app) + "\"" + ",\"v\":2" + ",\"iv\":\"" + b64e.encodeToString(iv) + "\"" + ",\"ct\":\"" + b64e.encodeToString(ct) + "\"" + ",\"tag\":\"" + b64e.encodeToString(tag) + "\"}"; String url = config.baseUrl.replaceAll("/+$", "") + "/api/v1.php"; HttpRequest req = HttpRequest.newBuilder(URI.create(url)) .timeout(Duration.ofSeconds(15)) .header("Content-Type", "application/json") .header("User-Agent", "PsychoKey-Java/" + config.version) .POST(HttpRequest.BodyPublishers.ofString(env, StandardCharsets.UTF_8)) .build(); HttpResponse resp = http.send(req, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8)); Map root = JsonMini.parseObject(resp.body()); Map payload; boolean encrypted = false; if (JsonMini.asLong(root.get("v"), 0) == 2L) { encrypted = true; Base64.Decoder b64d = Base64.getDecoder(); byte[] rIv = b64d.decode(JsonMini.asStr(root.get("iv"))); byte[] rCt = b64d.decode(JsonMini.asStr(root.get("ct"))); byte[] rTag = b64d.decode(JsonMini.asStr(root.get("tag"))); byte[] joined = new byte[rCt.length + rTag.length]; System.arraycopy(rCt, 0, joined, 0, rCt.length); System.arraycopy(rTag, 0, joined, rCt.length, rTag.length); byte[] respKey = hkdfSha256(secret, HKDF_SALT, "psychokey-resp-v2|" + config.app, 32); Cipher dec = Cipher.getInstance("AES/GCM/NoPadding"); dec.init(Cipher.DECRYPT_MODE, new SecretKeySpec(respKey, "AES"), new GCMParameterSpec(128, rIv)); dec.updateAAD((config.app + "|" + action + "|" + nonce).getBytes(StandardCharsets.UTF_8)); byte[] plain = dec.doFinal(joined); payload = JsonMini.parseObject(new String(plain, StandardCharsets.UTF_8)); } else { if (config.requireV2 && JsonMini.asBool(root.get("success"))) { out.code = "CLIENT_INTEGRITY"; out.message = "Unencrypted success rejected."; return out; } payload = root; } if (encrypted) { long respTs = JsonMini.asLong(payload.get("ts"), 0); if (respTs > 0 && Math.abs(respTs - ts) > 300) { out.code = "CLIENT_INTEGRITY"; out.message = "Response timestamp outside allowed window."; return out; } } out.ok = JsonMini.asBool(payload.get("success")); out.code = JsonMini.asStr(payload.get("code"), out.ok ? "OK" : "ERROR"); out.message = JsonMini.asStr(payload.get("message")); out.retryAfter = (int) JsonMini.asLong(payload.get("retry_after"), 0); out.latestVersion = JsonMini.asStr(payload.get("latest_version")); out.downloadUrl = JsonMini.asStr(payload.get("download_url")); Object vObj = payload.get("variables"); if (vObj instanceof Map) { for (Map.Entry e : ((Map) vObj).entrySet()) { if (e.getValue() instanceof String) { out.variables.put(String.valueOf(e.getKey()), (String) e.getValue()); } } } if (out.ok) { out.token = JsonMini.asStr(payload.get("token")); Object lObj = payload.get("license"); if (lObj instanceof Map) { @SuppressWarnings("unchecked") Map lm = (Map) lObj; out.license.id = JsonMini.asLong(lm.get("id"), 0); out.license.status = JsonMini.asStr(lm.get("status")); out.license.durationDays = (int) JsonMini.asLong(lm.get("duration"), 0); out.license.durationSeconds = (int) JsonMini.asLong(lm.get("duration_seconds"), 0); out.license.maxHwids = (int) JsonMini.asLong(lm.get("max_hwids"), 0); out.license.activatedAt = JsonMini.asStr(lm.get("activated_at")); out.license.expiresAt = JsonMini.asStr(lm.get("expires_at")); out.license.daysLeft = (int) JsonMini.asLong(lm.get("days_left"), -1); out.license.secondsLeft = JsonMini.asLong(lm.get("seconds_left"), -1); out.license.lifetime = JsonMini.asBool(lm.get("lifetime")); } } } catch (Exception ex) { out.code = "CLIENT_ERROR"; out.message = ex.getMessage() != null ? ex.getMessage() : ex.toString(); } return out; } private static byte[] hmacSha256(byte[] key, byte[] data) throws Exception { Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(key, "HmacSHA256")); return mac.doFinal(data); } private static byte[] hkdfSha256(byte[] ikm, String salt, String info, int len) throws Exception { byte[] prk = hmacSha256(salt.getBytes(StandardCharsets.UTF_8), ikm); byte[] infoB = info.getBytes(StandardCharsets.UTF_8); int n = (len + 31) / 32; byte[] okm = new byte[n * 32]; byte[] t = new byte[0]; for (int i = 1; i <= n; i++) { byte[] buf = new byte[t.length + infoB.length + 1]; System.arraycopy(t, 0, buf, 0, t.length); System.arraycopy(infoB, 0, buf, t.length, infoB.length); buf[buf.length - 1] = (byte) i; t = hmacSha256(prk, buf); System.arraycopy(t, 0, okm, (i - 1) * 32, 32); } byte[] out = new byte[len]; System.arraycopy(okm, 0, out, 0, len); return out; } private static String detectHwid() { String os = System.getProperty("os.name", "").toLowerCase(); String cand = ""; try { if (os.contains("win")) { Process p = new ProcessBuilder("wmic", "csproduct", "get", "UUID").start(); try (BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()))) { String line; while ((line = br.readLine()) != null) { String t = line.trim(); if (!t.isEmpty() && !t.equals("UUID")) { cand = t; break; } } } } else if (os.contains("nux") || os.contains("nix")) { for (String path : new String[]{"/etc/machine-id", "/var/lib/dbus/machine-id"}) { Path fp = Path.of(path); if (Files.isRegularFile(fp)) { String t = Files.readString(fp).trim(); if (!t.isEmpty()) { cand = t; break; } } } } else if (os.contains("mac")) { Process p = new ProcessBuilder("ioreg", "-rd1", "-c", "IOPlatformExpertDevice").start(); try (BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()))) { String line; while ((line = br.readLine()) != null) { if (line.contains("IOPlatformUUID")) { String[] parts = line.split("\""); if (parts.length >= 4) { cand = parts[parts.length - 2]; break; } } } } } } catch (Exception ignored) {} if (cand.matches("^[A-Za-z0-9:_-]{8,128}$")) return cand; try { String raw = System.getenv("COMPUTERNAME") + "|" + os + "|" + System.getProperty("os.arch", ""); byte[] d = MessageDigest.getInstance("SHA-256").digest(raw.getBytes(StandardCharsets.UTF_8)); return hexEncode(d).substring(0, 32); } catch (Exception e) { return "java_fallback_hwid_01"; } } private static String jsonEscape(String s) { if (s == null) return ""; StringBuilder sb = new StringBuilder(s.length()); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); switch (c) { case '\\': sb.append("\\\\"); break; case '"': sb.append("\\\""); break; case '\n': sb.append("\\n"); break; case '\r': sb.append("\\r"); break; case '\t': sb.append("\\t"); break; default: if (c < 0x20) sb.append(String.format("\\u%04x", (int) c)); else sb.append(c); } } return sb.toString(); } private static byte[] hexDecode(String hex) { if (hex.length() % 2 != 0) return new byte[0]; byte[] out = new byte[hex.length() / 2]; for (int i = 0; i < out.length; i++) { out[i] = (byte) Integer.parseInt(hex.substring(i * 2, i * 2 + 2), 16); } return out; } private static String hexEncode(byte[] b) { StringBuilder sb = new StringBuilder(b.length * 2); for (byte x : b) sb.append(String.format("%02x", x)); return sb.toString(); } } /** Tiny self-contained JSON parser so zero external JARs are needed. */ static final class JsonMini { private final String s; private int i; private JsonMini(String s) { this.s = s; } @SuppressWarnings("unchecked") static Map parseObject(String json) { Object v = new JsonMini(json).readValue(); return v instanceof Map ? (Map) v : new LinkedHashMap<>(); } static String asStr(Object o) { return asStr(o, ""); } static String asStr(Object o, String def) { return o instanceof String ? (String) o : def; } static boolean asBool(Object o) { return o instanceof Boolean && (Boolean) o; } static long asLong(Object o, long def) { return o instanceof Number ? ((Number) o).longValue() : def; } private void ws() { while (i < s.length() && Character.isWhitespace(s.charAt(i))) i++; } private Object readValue() { ws(); if (i >= s.length()) return null; char c = s.charAt(i); if (c == '{') return readObject(); if (c == '[') return readArray(); if (c == '"') return readString(); if (c == 't' && s.startsWith("true", i)) { i += 4; return Boolean.TRUE; } if (c == 'f' && s.startsWith("false", i)) { i += 5; return Boolean.FALSE; } if (c == 'n' && s.startsWith("null", i)) { i += 4; return null; } return readNumber(); } private Map readObject() { Map map = new LinkedHashMap<>(); i++; ws(); if (i < s.length() && s.charAt(i) == '}') { i++; return map; } while (i < s.length()) { ws(); String key = readString(); ws(); if (i < s.length() && s.charAt(i) == ':') i++; map.put(key, readValue()); ws(); if (i < s.length() && s.charAt(i) == ',') { i++; continue; } if (i < s.length() && s.charAt(i) == '}') { i++; break; } break; } return map; } private Object readArray() { var list = new java.util.ArrayList(); i++; ws(); if (i < s.length() && s.charAt(i) == ']') { i++; return list; } while (i < s.length()) { list.add(readValue()); ws(); if (i < s.length() && s.charAt(i) == ',') { i++; continue; } if (i < s.length() && s.charAt(i) == ']') { i++; break; } break; } return list; } private String readString() { if (i >= s.length() || s.charAt(i) != '"') return ""; i++; StringBuilder sb = new StringBuilder(); while (i < s.length()) { char c = s.charAt(i++); if (c == '"') break; if (c == '\\' && i < s.length()) { char e = s.charAt(i++); switch (e) { case '"': case '\\': case '/': sb.append(e); break; case 'b': sb.append('\b'); break; case 'f': sb.append('\f'); break; case 'n': sb.append('\n'); break; case 'r': sb.append('\r'); break; case 't': sb.append('\t'); break; case 'u': if (i + 4 <= s.length()) { sb.append((char) Integer.parseInt(s.substring(i, i + 4), 16)); i += 4; } break; default: sb.append(e); } } else { sb.append(c); } } return sb.toString(); } private Number readNumber() { int start = i; while (i < s.length() && "-0123456789.eE+".indexOf(s.charAt(i)) >= 0) i++; String raw = s.substring(start, i); try { if (raw.contains(".") || raw.contains("e") || raw.contains("E")) return Double.parseDouble(raw); return Long.parseLong(raw); } catch (Exception e) { return 0L; } } } }