# -*- coding: utf-8 -*-
"""Decode SHPSSDK obfuscated hex strings via uvuwwwuwu."""
import subprocess
import zipfile
from pathlib import Path

APK = Path(__file__).resolve().parent.parent / "apks" / "seabank_ph_base.apk"
DEXDUMP = Path(r"C:\Users\Administrator\AppData\Local\Android\Sdk\build-tools\37.0.0\dexdump.exe")

# sample pairs from SHPSSDK.wwwwvwwwu
samples = [
    ("0F580514065B111F0E1A10", "wuvuvvwvv"),
    ("100F3C013C1C19113F18271F3A36371F2C253C403F323C053F353C013F1C19123F1F3C4F", "uvvvuvvvv"),
    ("0E5806170758131F0D1B10", "vuuvwuuvu"),
    ("120E3D023E1C1A113C1A261E3934371C2C263E413E313A053C353F033E1D1A103F1C3C4C", "wwwuwvuvu"),
]

# dump uvuwwwuwu implementation
with zipfile.ZipFile(str(APK)) as zf:
    tmp = Path(__file__).resolve().parent.parent / "tmp" / "tmp11.dex"
    tmp.write_bytes(zf.read("classes11.dex"))
    out = subprocess.check_output(
        [str(DEXDUMP), "-d", str(tmp)], universal_newlines=True, errors="replace"
    )
    cap = False
    print("=== uvuwwwuwu implementation ===")
    for line in out.splitlines():
        if "uvuwwwuwu:(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;" in line:
            cap = True
        if cap:
            print(line.encode("ascii", "replace").decode())
            if cap and "locals        :" in line:
                break

print("\n=== try XOR decode (common pattern) ===")
for hex_str, key in samples:
    data = bytes.fromhex(hex_str) if all(c in "0123456789ABCDEFabcdef" for c in hex_str) else hex_str.encode()
    # try simple xor with key bytes cycling
    kb = key.encode()
    dec = bytes(b ^ kb[i % len(kb)] for i, b in enumerate(data))
    try:
        txt = dec.decode("utf-8")
    except Exception:
        txt = dec.decode("latin1", errors="replace")
    print(hex_str[:20], "...", "->", repr(txt[:80]))
