untitled

Pasted Nov 14, 2026, 2:38 PM1 file456 lines

Scan to open on your phone

Point a camera at the QR code - it opens this exact paste, no app needed.

https://codepastes.com/zzgs59vghmn84sjt
untitled
import usb.core
import usb.util
import libusb_package
import threading
import time
import msvcrt
import colorsys
import os
import glob
import random

# --- VALÓDI SKYLANDERS KRIPTOGRÁFIA & CRC ---
def calc_crc48(data):
    crc = 0x0000FFFFFFFFFFFF
    poly = 0x42F0E1EBA9EA3693
    for byte in data:
        crc ^= (byte << 40)
        for _ in range(8):
            if crc & 0x800000000000:
                crc = ((crc << 1) ^ poly) & 0xFFFFFFFFFFFF
            else:
                crc = (crc << 1) & 0xFFFFFFFFFFFF
    return crc

def calc_crc16(data):
    crc = 0xFFFF
    for byte in data:
        crc ^= (byte << 8)
        for _ in range(8):
            if crc & 0x8000:
                crc = ((crc << 1) ^ 0x1021) & 0xFFFF
            else:
                crc = (crc << 1) & 0xFFFF
    return crc

SKYLANDERS_KEY_MAGIC = b"2 * 4 + 1"

def get_skylander_key_a(uid_bytes, sector):
    if sector == 0:
        return bytes([0x4B, 0x0B, 0x20, 0x10, 0x7C, 0xCB])
    crc = calc_crc48(SKYLANDERS_KEY_MAGIC + uid_bytes + bytes([sector]))
    return crc.to_bytes(6, byteorder='little')

# --- USB PORTAL INICIALIZÁLÁS ---
dev = libusb_package.find(idVendor=0x1430, idProduct=0x0150)
if dev is None:
    raise ValueError("Nem található a Spyro Porta (VID: 0x1430, PID: 0x0150)!")

dev.set_configuration()
usb.util.claim_interface(dev, 0)

running = True
rainbow_mode = False
usb_lock = threading.Lock()
last_mask = -1
active_slot = 0
working_prefix = 0x10
last_read_data = None
read_event = threading.Event()
write_event = threading.Event()
last_write_ok = False

def send_cmd(data_bytes):
    packet = list(data_bytes) + [0x00] * (32 - len(data_bytes))
    with usb_lock:
        dev.ctrl_transfer(0x21, 0x09, 0x0200, 0x0000, packet)

def parse_and_print(resp):
    global last_mask, active_slot, last_read_data, last_write_ok
    cmd = resp[0]
    
    if cmd == 0x53:  # 'S' - Státusz
        presence_mask = int.from_bytes(resp[1:5], byteorder='little')
        antenna_on = resp[6] == 0x01
        
        found_slot = None
        for i in range(16):
            state = (presence_mask >> (i * 2)) & 0b11
            if state in (0b01, 0b11):
                found_slot = i
                break
        if found_slot is not None:
            active_slot = found_slot

        if presence_mask != last_mask:
            last_mask = presence_mask
            slots = []
            newly_placed = False
            for i in range(16):
                state = (presence_mask >> (i * 2)) & 0b11
                if state in (0b01, 0b11):
                    slots.append(f"Slot {i} (AKTÍV)")
                    if state == 0b11:
                        newly_placed = True
                elif state == 0b10:
                    slots.append(f"Slot {i} (LEVÉVE)")
            status_txt = ", ".join(slots) if slots else "Üres portál"
            print(f"\n[STÁTUSZ] Antenna: {'BE' if antenna_on else 'KI'} | {status_txt} (Célslot: {active_slot})")
            if newly_placed:
                threading.Thread(target=quick_identify, daemon=True).start()

    elif cmd == 0x51:  # 'Q' - Blokk olvasás válasz
        status = resp[1]
        data = list(resp[3:19])
        last_read_data = data if (status & 0x10) else None
        read_event.set()

    elif cmd == 0x57:  # 'W' - Blokk írás válasz
        last_write_ok = bool(resp[1] & 0x10)
        write_event.set()

    elif cmd == 0x41:  # 'A' - Antenna
        print(f"[ANTENNA] {'BEKAPCSOLVA' if resp[1] == 0x01 else 'KIKAPCSOLVA'}")

    elif cmd == 0x52:  # 'R' - Reset
        active_slot = 0
        ver = " ".join(f"{b:02X}" for b in resp[1:5])
        print(f"[RESET] Portál újraindítva (Verzió: {ver})")

def read_single_block(block_num):
    global working_prefix
    for attempt in range(3):
        prefixes = [working_prefix] + [p for p in (0x10, 0x00, 0x20) if p != working_prefix]
        for prefix in prefixes:
            read_event.clear()
            send_cmd([0x51, prefix + active_slot, block_num])
            if read_event.wait(timeout=0.35) and last_read_data is not None:
                working_prefix = prefix
                return bytes(last_read_data)
        time.sleep(0.05)
    return None

def write_single_block(block_num, data_16_bytes):
    write_event.clear()
    cmd = [0x57, working_prefix + active_slot, block_num] + list(data_16_bytes)
    send_cmd(cmd)
    if write_event.wait(timeout=0.5):
        return last_write_ok
    return False

def quick_identify():
    time.sleep(0.2)
    b0 = read_single_block(0)
    b1 = read_single_block(1)
    if b0 and b1:
        uid = b0[0:4].hex(' ').upper()
        char_id = int.from_bytes(b1[0:2], byteorder='little')
        var_id = int.from_bytes(b1[12:14], byteorder='little')
        print(f"   >>> Figura észlelve [Slot {active_slot}] | UID: [{uid}] | SAK: 0x{b0[5]:02X} | Karakter ID: {char_id} | Variáns: {var_id} <<<")

def repair_sak_to_standard():
    print(f"\n--- KORONG SAK=0x08 VISSZAÁLLÍTÁSA (Slot {active_slot}) ---")
    b0 = read_single_block(0)
    if not b0:
        print("[HIBA] Nem olvasható a 0. blokk! Tedd a korongot pontosan a portál közepére.")
        return
    print(f"Jelenlegi 0. blokk: {b0.hex(' ').upper()} (SAK=0x{b0[5]:02X}, ATQA={b0[6:8].hex().upper()})")
    new_b0 = bytearray(b0)
    new_b0[5] = 0x08
    new_b0[6] = 0x04
    new_b0[7] = 0x00
    if write_single_block(0, new_b0):
        print(f"[SIKER] Visszaállítva: {new_b0.hex(' ').upper()} -> Most már látja a telefonos MCT!\n")
    else:
        print("[HIBA] A portál nem tudta felülírni a 0. blokkot.\n")

def read_and_print_to_console():
    print(f"\n================ NFC CHIP TELJES KIOLVASÁSA (Slot {active_slot}) ================")
    raw_dump = bytearray()
    for block in range(64):
        data = read_single_block(block)
        if data is None:
            print(f"[HIBA] Megszakadt a(z) {block}. blokknál a(z) {active_slot}. sloton!")
            return None
        raw_dump.extend(data)
        time.sleep(0.04)

    uid = bytes(raw_dump[0:4])
    bcc = raw_dump[4]
    calc_bcc = uid[0] ^ uid[1] ^ uid[2] ^ uid[3]
    char_id = int.from_bytes(raw_dump[16:18], byteorder='little')
    var_id = int.from_bytes(raw_dump[28:30], byteorder='little')
    crc_type0 = int.from_bytes(raw_dump[30:32], byteorder='little')
    calc_type0 = calc_crc16(raw_dump[0:30])

    print(f"UID          : {uid.hex(' ').upper()} (BCC: 0x{bcc:02X} | Számolt: 0x{calc_bcc:02X} -> {'OK' if bcc == calc_bcc else 'HIBÁS'})")
    print(f"SAK / ATQA   : SAK=0x{raw_dump[5]:02X} | ATQA={raw_dump[6:8].hex().upper()}")
    print(f"Karakter ID  : {char_id} (0x{char_id:04X}) | Variáns ID: {var_id} (0x{var_id:04X})")
    print(f"Header CRC16 : 0x{crc_type0:04X} ({'OK' if crc_type0 == calc_type0 else 'ELTÉRŐ'})")
    print("-" * 82)

    for sector in range(16):
        calc_key = get_skylander_key_a(uid, sector).hex().upper()
        print(f"--- Szektor {sector:02d} (Számolt Skylanders Key A: {calc_key}) ---")
        for blk in range(4):
            b_idx = sector * 4 + blk
            b_bytes = raw_dump[b_idx * 16 : (b_idx + 1) * 16]
            hex_part = " ".join(f"{x:02X}" for x in b_bytes)
            ascii_part = "".join(chr(x) if 32 <= x <= 126 else "." for x in b_bytes)
            tag_type = " [TRAILER]" if blk == 3 else (" [UID/MFG]" if b_idx == 0 else "")
            print(f"  Blokk {b_idx:02d}: {hex_part}  |  {ascii_part}{tag_type}")
    print("=====================================================================\n")
    return raw_dump

def inspect_single_block():
    val = input(f"\nMelyik blokkot olvassam ki a(z) {active_slot}. slotról? (0-63): ").strip()
    if not val.isdigit() or not (0 <= int(val) <= 63):
        print("[HIBA] Érvénytelen blokkszám!")
        return
    b_idx = int(val)
    data = read_single_block(b_idx)
    if data:
        print(f"\n[Slot {active_slot} | Blokk {b_idx:02d} | Szektor {b_idx//4:02d}]")
        print(f"  HEX  : {' '.join(f'{x:02X}' for x in data)}\n")
    else:
        print(f"[HIBA] A(z) {b_idx}. blokk nem olvasható.")

def save_mct_only(data):
    uid = bytes(data[0:4])
    uid_str = uid.hex().upper()
    char_id = int.from_bytes(data[16:18], byteorder='little')

    # CUID kompatibilitás: SAK=0x08 és ATQA=04 00, hogy az Android NFC ne tiltsa le
    data[5] = 0x08
    data[6] = 0x04
    data[7] = 0x00

    for sector in range(16):
        trailer_offset = (sector * 4 + 3) * 16
        key_a = get_skylander_key_a(uid, sector)
        access_bits = bytes([0x7F, 0x0F, 0x08, 0x69]) if sector == 0 else bytes([0xFF, 0x07, 0x80, 0x69])
        data[trailer_offset : trailer_offset + 16] = key_a + access_bits + bytes([0xFF] * 6)

    mct_filename = f"Skylander_ID{char_id:04d}_{uid_str}.mct"
    mct_path = os.path.abspath(mct_filename)

    lines = []
    for sector in range(16):
        lines.append(f"+Sector: {sector}")
        for blk in range(4):
            offset = (sector * 4 + blk) * 16
            lines.append(data[offset : offset + 16].hex().upper())

    with open(mct_path, "w", encoding="ascii", newline="\n") as f:
        f.write("\n".join(lines))

    keys_path = os.path.abspath(f"Skylander_ID{char_id:04d}_{uid_str}.keys")
    unique_keys = sorted({get_skylander_key_a(uid, s).hex().upper() for s in range(16)} | {"FFFFFFFFFFFF"})
    with open(keys_path, "w", encoding="ascii", newline="\n") as f:
        f.write("\n".join(unique_keys))

    print(f"\n--- SIKERES MENTÉS ---")
    print(f"MCT Fájl : {mct_path}")
    print(f"KEYS Fájl: {keys_path}\n")

def generate_custom_character_mct():
    print("\n--- ÚJ EGYEDI FIGURA (.MCT) GENERÁLÁSA KÜLÖN NFC CHIPHEZ ---")
    print("Példák: Hot Head = ID: 104, Variáns: 4614 | Spyro = ID: 16, Variáns: 0")
    c_str = input("Karakter ID (pl. 104): ").strip()
    v_str = input("Variáns ID (pl. 4614, ha nincs akkor 0): ").strip()
    if not c_str.isdigit() or not v_str.isdigit():
        print("[HIBA] Csak egész számot adj meg! Megszakítva.\n")
        return

    char_id = int(c_str)
    var_id = int(v_str)

    data = bytearray(1024)
    uid = bytes([random.choice([b for b in range(1, 255) if b != 0x88])] + [random.randint(0, 255) for _ in range(3)])
    bcc = uid[0] ^ uid[1] ^ uid[2] ^ uid[3]

    data[0:4] = uid
    data[4] = bcc
    data[5] = 0x08
    data[6:8] = bytes([0x04, 0x00])
    data[8:16] = bytes([0xC4, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, 0x13])

    data[16:18] = char_id.to_bytes(2, byteorder='little')
    data[20:28] = bytes([0xCB, 0xAE, 0xBC, 0xE1, 0x08, 0x7C, 0x00, 0x00])
    data[28:30] = var_id.to_bytes(2, byteorder='little')
    header_crc = calc_crc16(data[0:30])
    data[30:32] = header_crc.to_bytes(2, byteorder='little')

    print(f"\nGenerált UID : {uid.hex(' ').upper()} | SAK: 0x08 | Karakter ID: {char_id} | Variáns: {var_id} | CRC16: 0x{header_crc:04X}")
    save_mct_only(data)

def dump_to_mct():
    print(f"\n--- Figura mentése MCT fájlba (Slot {active_slot}) ---")
    data = bytearray()
    for block in range(64):
        b = read_single_block(block)
        if b is None:
            print(f"\n[HIBA] Megszakadt a(z) {block}. blokknál!")
            return
        data.extend(b)
        print(f"\rOlvasás: {block + 1}/64 blokk", end="", flush=True)
        time.sleep(0.04)
    save_mct_only(data)

def modify_character_id():
    b1 = read_single_block(1)
    if not b1:
        print(f"\n[HIBA] Nem olvasható az 1. blokk a(z) {active_slot}. sloton!")
        return
    cur_id = int.from_bytes(b1[0:2], byteorder='little')
    cur_var = int.from_bytes(b1[12:14], byteorder='little')
    print(f"\nJelenlegi Karakter ID: {cur_id} (0x{cur_id:04X}) | Variáns: {cur_var} (0x{cur_var:04X})")
    
    new_id_str = input("Új Karakter ID (decimálisan, pl. 104 = Hot Head): ").strip()
    new_var_str = input("Új Variáns ID (decimálisan, pl. 4614 = Hot Head, vagy 0): ").strip()
    if not new_id_str.isdigit() or not new_var_str.isdigit():
        print("Megszakítva.")
        return
    new_id = int(new_id_str)
    new_var = int(new_var_str)
    
    b0 = read_single_block(0)
    if not b0:
        print("[HIBA] Nem olvasható a 0. blokk a CRC számításhoz!")
        return

    new_b1 = bytearray(b1)
    new_b1[0:2] = new_id.to_bytes(2, byteorder='little')
    new_b1[12:14] = new_var.to_bytes(2, byteorder='little')
    new_crc = calc_crc16(b0 + bytes(new_b1[0:14]))
    new_b1[14:16] = new_crc.to_bytes(2, byteorder='little')

    if write_single_block(1, new_b1):
        print(f"[SIKER] Karakter ID: {new_id}, Variáns: {new_var} (Új Header CRC16: 0x{new_crc:04X})!\n")
    else:
        print("[HIBA] Nem sikerült írni az 1. blokkot.\n")

def restore_mct_to_tag():
    mct_files = sorted(glob.glob("*.mct"), key=os.path.getmtime, reverse=True)
    if not mct_files:
        print("\n[HIBA] Nincs .mct fájl a mappában!")
        return
    for idx, fname in enumerate(mct_files):
        print(f"[{idx}] {fname}")
    choice = input("Válassz .mct fájlt (szám): ").strip()
    if not choice.isdigit() or int(choice) >= len(mct_files):
        return

    with open(mct_files[int(choice)], "r") as f:
        lines = [line.strip() for line in f if line.strip() and not line.startswith("+")]
    if len(lines) != 64:
        print("[HIBA] Hibás .mct fájl (nem 64 blokk)!")
        return

    ok, fail = 0, 0
    for block in range(1, 64):
        if (block + 1) % 4 == 0:
            continue
        block_bytes = bytes.fromhex(lines[block])
        if write_single_block(block, block_bytes):
            ok += 1
            print(f"\rÍrás (Slot {active_slot}): Blokk {block:02d}/63 OK", end="", flush=True)
        else:
            fail += 1
        time.sleep(0.04)
    print(f"\n[KÉSZ] Sikeres blokkok: {ok} | Sikertelen: {fail}\n")

def reader_loop():
    while running:
        try:
            with usb_lock:
                resp = dev.read(0x81, 32, timeout=30)
            parse_and_print(resp)
        except usb.core.USBTimeoutError:
            pass
        except Exception as e:
            if running:
                print(f"[HIBA] {e}")
            break

def rainbow_loop():
    hue = 0.0
    while running:
        if rainbow_mode:
            r, g, b = [int(c * 255) for c in colorsys.hsv_to_rgb(hue, 1.0, 1.0)]
            send_cmd([0x43, r, g, b])
            hue = (hue + 0.01) % 1.0
        time.sleep(0.05)

threading.Thread(target=reader_loop, daemon=True).start()
threading.Thread(target=rainbow_loop, daemon=True).start()
send_cmd([0x41, 0x01])

def print_menu():
    print("\n================ SKYLANDERS PORTAL MASTER TOOL ================")
    print("  [Z] CHIP MENTÉS : SAK=0x81 visszaállítása SAK=0x08-ra (MCT-hez)")
    print("  [G] ÚJ FIGURA   : Tetszőleges Karakter + Variáns ID -> .mct + .keys")
    print("  [C] KONZOL DUMP : Teljes 64 blokk kiolvasása & dekódolása képernyőre")
    print("  [B] BLOKK OLV.  : Egy konkrét blokk (0-63) HEX/ASCII vizsgálata")
    print("  [D] MCT MENTÉS  : Kiolvasás + CUID SAK=08 + CRC48 -> .mct + .keys")
    print("  [I] PORTÁL ÍRÁS : .mct adatblokkok visszaírása kulcsos chipre")
    print("  [K] KARAKTER ID : Chip Karakter + Variáns ID átírása portálon")
    print("  [1/2] Antenna BE/KI | [3/4/5/6] Piros/Zöld/Kék/KI | [S] Szivárvány")
    print("  [R] Portál Reset (Slot 0 visszaállítása) | [H] Menü | [ESC] Kilépés")
    print("===============================================================")

print_menu()

try:
    while running:
        if msvcrt.kbhit():
            ch = msvcrt.getch()
            if ch == b'\x1b':
                running = False
                break
            key = ch.decode('utf-8', errors='ignore').lower()
            if key == 'z':
                repair_sak_to_standard()
            elif key == 'g':
                generate_custom_character_mct()
            elif key == 'c':
                read_and_print_to_console()
            elif key == 'b':
                inspect_single_block()
            elif key == 'd':
                dump_to_mct()
            elif key == 'i':
                restore_mct_to_tag()
            elif key == 'k':
                modify_character_id()
            elif key == '1':
                send_cmd([0x41, 0x01])
            elif key == '2':
                send_cmd([0x41, 0x00])
            elif key == '3':
                rainbow_mode = False
                send_cmd([0x43, 0xFF, 0x00, 0x00])
            elif key == '4':
                rainbow_mode = False
                send_cmd([0x43, 0x00, 0xFF, 0x00])
            elif key == '5':
                rainbow_mode = False
                send_cmd([0x43, 0x00, 0x00, 0xFF])
            elif key == '6':
                rainbow_mode = False
                send_cmd([0x43, 0x00, 0x00, 0x00])
            elif key == 's':
                rainbow_mode = not rainbow_mode
                print(f">> Szivárvány mód: {'BE' if rainbow_mode else 'KI'}")
            elif key == 'r':
                rainbow_mode = False
                send_cmd([0x52])
            elif key == 'h':
                print_menu()
        time.sleep(0.02)
except KeyboardInterrupt:
    running = False

usb.util.release_interface(dev, 0)
print("Kapcsolat bontva.")

17,086 chars · codepastes.com