// Psycho Key — Go SDK (v2 AES-256-GCM protocol) // Uses ONLY the Go standard library (Go 1.18+, zero third-party dependencies). // // Usage: // client, err := psychokey.NewClient(psychokey.Config{ // App: "my-app", // ApiSecret: "64_HEX_CHARS", // }) // res := client.Auth("PSYCHO-XXXX-XXXX-XXXX-XXXX") // if res.Ok { fmt.Println("Days left:", res.License.DaysLeft) } package psychokey import ( "bytes" "crypto/aes" "crypto/cipher" "crypto/hmac" "crypto/rand" "crypto/sha256" "encoding/base64" "encoding/hex" "encoding/json" "errors" "fmt" "io" "math" "net/http" "os" "os/exec" "regexp" "runtime" "strings" "sync" "time" ) const ( hkdfSalt = "psychokey-salt-v1" defaultBase = "https://psycho-key.com" ) var validHwidRe = regexp.MustCompile(`^[A-Za-z0-9:_\-]{8,128}$`) type Config struct { App string ApiSecret string // 64 hex chars (32 bytes) BaseURL string // default: https://psycho-key.com Version string // default: 1.0.0 RequireV2 *bool // default: true } type License struct { ID int64 `json:"id"` Status string `json:"status"` DurationDays int `json:"duration"` DurationSeconds int `json:"duration_seconds"` MaxHwids int `json:"max_hwids"` ActivatedAt string `json:"activated_at"` ExpiresAt string `json:"expires_at"` DaysLeft int `json:"days_left"` SecondsLeft int64 `json:"seconds_left"` Lifetime bool `json:"lifetime"` } type Result struct { Ok bool Code string Message string Token string RetryAfter int LatestVersion string DownloadURL string Variables map[string]string License License } type Client struct { mu sync.Mutex config Config secret []byte requireV2 bool hwid string token string vars map[string]string http *http.Client } func NewClient(cfg Config) (*Client, error) { secret, err := hex.DecodeString(strings.TrimSpace(cfg.ApiSecret)) if err != nil || len(secret) != 32 { return nil, errors.New("ApiSecret must be exactly 64 hex chars (32 bytes)") } if strings.TrimSpace(cfg.BaseURL) == "" { cfg.BaseURL = defaultBase } cfg.BaseURL = strings.TrimRight(cfg.BaseURL, "/") if strings.TrimSpace(cfg.Version) == "" { cfg.Version = "1.0.0" } reqV2 := true if cfg.RequireV2 != nil { reqV2 = *cfg.RequireV2 } return &Client{ config: cfg, secret: secret, requireV2: reqV2, hwid: detectHWID(), vars: make(map[string]string), http: &http.Client{Timeout: 15 * time.Second}, }, nil } func (c *Client) HWID() string { return c.hwid } func (c *Client) Var(key string, fallback ...string) string { c.mu.Lock() defer c.mu.Unlock() if v, ok := c.vars[key]; ok { return v } if len(fallback) > 0 { return fallback[0] } return "" } func (c *Client) Init() Result { return c.call("init", "") } func (c *Client) Auth(licenseKey string) Result { r := c.call("license", licenseKey) c.mu.Lock() if r.Ok && r.Token != "" { c.token = r.Token } for k, v := range r.Variables { c.vars[k] = v } c.mu.Unlock() return r } func (c *Client) Heartbeat() Result { r := c.call("heartbeat", "") c.mu.Lock() if r.Ok && r.Token != "" { c.token = r.Token } for k, v := range r.Variables { c.vars[k] = v } c.mu.Unlock() return r } func (c *Client) Logout() Result { r := c.call("logout", "") c.mu.Lock() c.token = "" c.mu.Unlock() return r } func (c *Client) ResetHWID(licenseKey string) Result { r := c.call("reset", licenseKey) c.mu.Lock() if r.Ok && r.Token != "" { c.token = r.Token } for k, v := range r.Variables { c.vars[k] = v } c.mu.Unlock() return r } func (c *Client) call(action, licenseKey string) Result { out := Result{Variables: make(map[string]string), License: License{DaysLeft: -1, SecondsLeft: -1}} nonceBytes := make([]byte, 16) if _, err := rand.Read(nonceBytes); err != nil { out.Code, out.Message = "CLIENT_CRYPTO", err.Error() return out } nonce := hex.EncodeToString(nonceBytes) ts := time.Now().Unix() c.mu.Lock() curToken := c.token c.mu.Unlock() canonical := strings.Join([]string{ c.config.App, action, nonce, fmt.Sprintf("%d", ts), c.hwid, licenseKey, curToken, }, "|") mac := hmac.New(sha256.New, c.secret) mac.Write([]byte(canonical)) sig := hex.EncodeToString(mac.Sum(nil)) innerObj := map[string]any{ "action": action, "nonce": nonce, "ts": ts, "hwid": c.hwid, "license_key": licenseKey, "token": curToken, "version": c.config.Version, "sig": sig, } innerBytes, err := json.Marshal(innerObj) if err != nil { out.Code, out.Message = "CLIENT_ENCODE", err.Error() return out } reqKey := hkdfSha256(c.secret, []byte(hkdfSalt), []byte("psychokey-req-v2|"+c.config.App), 32) iv, ct, tag, err := aesGcmEncrypt(reqKey, innerBytes, []byte(c.config.App)) if err != nil { out.Code, out.Message = "CLIENT_CRYPTO", err.Error() return out } envBytes, _ := json.Marshal(map[string]any{ "app": c.config.App, "v": 2, "iv": base64.StdEncoding.EncodeToString(iv), "ct": base64.StdEncoding.EncodeToString(ct), "tag": base64.StdEncoding.EncodeToString(tag), }) req, err := http.NewRequest("POST", c.config.BaseURL+"/api/v1.php", bytes.NewReader(envBytes)) if err != nil { out.Code, out.Message = "NETWORK", err.Error() return out } req.Header.Set("Content-Type", "application/json") req.Header.Set("User-Agent", "PsychoKey-Go/"+c.config.Version) resp, err := c.http.Do(req) if err != nil { out.Code, out.Message = "NETWORK", err.Error() return out } defer resp.Body.Close() body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) if err != nil { out.Code, out.Message = "NETWORK", err.Error() return out } var root map[string]json.RawMessage if err := json.Unmarshal(body, &root); err != nil { out.Code, out.Message = "CLIENT_PARSE", err.Error() return out } var payloadMap map[string]any encrypted := false var vNum int if rawV, ok := root["v"]; ok { _ = json.Unmarshal(rawV, &vNum) } if vNum == 2 { encrypted = true var ivB64, ctB64, tagB64 string _ = json.Unmarshal(root["iv"], &ivB64) _ = json.Unmarshal(root["ct"], &ctB64) _ = json.Unmarshal(root["tag"], &tagB64) rIv, err1 := base64.StdEncoding.DecodeString(ivB64) rCt, err2 := base64.StdEncoding.DecodeString(ctB64) rTag, err3 := base64.StdEncoding.DecodeString(tagB64) if err1 != nil || err2 != nil || err3 != nil { out.Code, out.Message = "CLIENT_PARSE", "Invalid base64 fields." return out } respKey := hkdfSha256(c.secret, []byte(hkdfSalt), []byte("psychokey-resp-v2|"+c.config.App), 32) aad := []byte(c.config.App + "|" + action + "|" + nonce) plain, err := aesGcmDecrypt(respKey, rIv, rCt, rTag, aad) if err != nil { out.Code, out.Message = "CLIENT_INTEGRITY", "Response authentication failed." return out } if err := json.Unmarshal(plain, &payloadMap); err != nil { out.Code, out.Message = "CLIENT_PARSE", err.Error() return out } } else { if err := json.Unmarshal(body, &payloadMap); err != nil { out.Code, out.Message = "CLIENT_PARSE", err.Error() return out } if okFlag, _ := payloadMap["success"].(bool); okFlag && c.requireV2 { out.Code, out.Message = "CLIENT_INTEGRITY", "Unencrypted success rejected." return out } } if encrypted { if rTs, ok := payloadMap["ts"].(float64); ok && rTs > 0 { if math.Abs(rTs-float64(ts)) > 300.0 { out.Code, out.Message = "CLIENT_INTEGRITY", "Response timestamp outside allowed window." return out } } } out.Ok, _ = payloadMap["success"].(bool) if s, ok := payloadMap["code"].(string); ok { out.Code = s } else if out.Ok { out.Code = "OK" } else { out.Code = "ERROR" } out.Message, _ = payloadMap["message"].(string) if ra, ok := payloadMap["retry_after"].(float64); ok { out.RetryAfter = int(ra) } out.LatestVersion, _ = payloadMap["latest_version"].(string) out.DownloadURL, _ = payloadMap["download_url"].(string) if vars, ok := payloadMap["variables"].(map[string]any); ok { for k, v := range vars { if vs, ok := v.(string); ok { out.Variables[k] = vs } } } if out.Ok { out.Token, _ = payloadMap["token"].(string) if licRaw, ok := payloadMap["license"]; ok { licBytes, _ := json.Marshal(licRaw) _ = json.Unmarshal(licBytes, &out.License) } } return out } func hkdfSha256(ikm, salt, info []byte, length int) []byte { ext := hmac.New(sha256.New, salt) ext.Write(ikm) prk := ext.Sum(nil) n := (length + 31) / 32 okm := make([]byte, 0, n*32) var prev []byte for i := 1; i <= n; i++ { exp := hmac.New(sha256.New, prk) exp.Write(prev) exp.Write(info) exp.Write([]byte{byte(i)}) prev = exp.Sum(nil) okm = append(okm, prev...) } return okm[:length] } func aesGcmEncrypt(key, plaintext, aad []byte) (iv, ct, tag []byte, err error) { block, err := aes.NewCipher(key) if err != nil { return nil, nil, nil, err } gcm, err := cipher.NewGCM(block) if err != nil { return nil, nil, nil, err } iv = make([]byte, 12) if _, err := rand.Read(iv); err != nil { return nil, nil, nil, err } sealed := gcm.Seal(nil, iv, plaintext, aad) ct = sealed[:len(sealed)-16] tag = sealed[len(sealed)-16:] return iv, ct, tag, nil } func aesGcmDecrypt(key, iv, ct, tag, aad []byte) ([]byte, error) { block, err := aes.NewCipher(key) if err != nil { return nil, err } gcm, err := cipher.NewGCM(block) if err != nil { return nil, err } joined := make([]byte, len(ct)+len(tag)) copy(joined, ct) copy(joined[len(ct):], tag) return gcm.Open(nil, iv, joined, aad) } func detectHWID() string { var cand string switch runtime.GOOS { case "windows": if out, err := exec.Command("wmic", "csproduct", "get", "UUID").Output(); err == nil { for _, line := range strings.Split(string(out), "\n") { t := strings.TrimSpace(line) if t != "" && t != "UUID" { cand = t break } } } case "linux": for _, p := range []string{"/etc/machine-id", "/var/lib/dbus/machine-id"} { if b, err := os.ReadFile(p); err == nil { if t := strings.TrimSpace(string(b)); t != "" { cand = t break } } } case "darwin": if out, err := exec.Command("ioreg", "-rd1", "-c", "IOPlatformExpertDevice").Output(); err == nil { for _, line := range strings.Split(string(out), "\n") { if strings.Contains(line, "IOPlatformUUID") { parts := strings.Split(line, "\"") if len(parts) >= 4 { cand = parts[len(parts)-2] break } } } } } if validHwidRe.MatchString(cand) { return cand } host, _ := os.Hostname() sum := sha256.Sum256([]byte(host + "|" + runtime.GOOS + "|" + runtime.GOARCH)) return hex.EncodeToString(sum[:16]) }