Загрузка данных


import socket
import json
import re

HOST = 'tasks.duckerz.ru'
PORT = 30009

def test_payload(payload_dict, label):
    """Пробует отправить JSON и вернуть ответ."""
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(5.0)
    try:
        s.connect((HOST, PORT))
        data = b""
        while b"Send to Bob:" not in data:
            chunk = s.recv(4096)
            if not chunk:
                break
            data += chunk
        
        text = data.decode('utf-8', errors='ignore')
        match = re.search(r'\{.*\}', text)
        if not match:
            return None
        
        alice = json.loads(match.group())
        p = int(alice['p'], 16)
        g = int(alice['g'], 16)
        
        c = 1337
        C = pow(g, c, p)
        
        # Подставляем C в payload
        payload = json.dumps({k: (v if v != 'C' else C) for k, v in payload_dict.items()})
        # Или проще:
        if 'C' in payload_dict:
            payload_dict['C'] = C
        if 'answer' in payload_dict:
            payload_dict['answer'] = C
        if 'pub' in payload_dict:
            payload_dict['pub'] = C
        if 'key' in payload_dict:
            payload_dict['key'] = C
        
        payload = json.dumps(payload_dict)
        s.sendall((payload + "\n").encode())
        
        resp = s.recv(4096).decode('utf-8', errors='ignore').strip()
        if resp and "Connection terminated" not in resp:
            print(f"[+] УСПЕХ с '{label}'!")
            print(f"    Ответ: {resp[:300]}")
            return resp
    except Exception as e:
        pass
    finally:
        s.close()
    return None

# Перебираем форматы
formats = [
    ({"C": "PLACEHOLDER"}, "C (int)"),
    ({"C": "PLACEHOLDER"}, "C (str)"),
    ({"C": "PLACEHOLDER"}, "C (hex)"),
    ({"C": "PLACEHOLDER"}, "C (hex без 0x)"),
    ({"answer": "PLACEHOLDER"}, "answer (int)"),
    ({"answer": "PLACEHOLDER"}, "answer (str)"),
    ({"answer": "PLACEHOLDER"}, "answer (hex)"),
    ({"pub": "PLACEHOLDER"}, "pub (int)"),
    ({"key": "PLACEHOLDER"}, "key (int)"),
    ({"B": "PLACEHOLDER"}, "B (int)"),
]

# Но нам нужно подставлять разные типы значений
# Поэтому сделаем иначе - передадим функцию
def make_test(key_name, val_type):
    def test():
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(5.0)
        try:
            s.connect((HOST, PORT))
            data = b""
            while b"Send to Bob:" not in data:
                chunk = s.recv(4096)
                if not chunk:
                    break
                data += chunk
            
            text = data.decode('utf-8', errors='ignore')
            match = re.search(r'\{.*\}', text)
            alice = json.loads(match.group())
            p = int(alice['p'], 16)
            g = int(alice['g'], 16)
            
            c = 1337
            C = pow(g, c, p)
            
            if val_type == 'int':
                val = C
            elif val_type == 'str':
                val = str(C)
            elif val_type == 'hex':
                val = hex(C)
            elif val_type == 'hex_no_prefix':
                val = hex(C)[2:]
            elif val_type == 'hex_format':
                val = format(C, 'x')
            else:
                val = C
            
            payload = json.dumps({key_name: val})
            s.sendall((payload + "\n").encode())
            
            resp = s.recv(4096).decode('utf-8', errors='ignore').strip()
            if resp and "Connection terminated" not in resp:
                print(f"[+] УСПЕХ! Ключ='{key_name}', Тип='{val_type}'")
                print(f"    Ответ: {resp[:300]}")
                return resp
        except Exception as e:
            pass
        finally:
            s.close()
        return None
    return test

# Перебираем
keys = ['C', 'answer', 'pub', 'key', 'B', 'g', 'p']
val_types = ['int', 'str', 'hex', 'hex_no_prefix', 'hex_format']

print("[*] Перебираем ключи и типы значений...")
found = False
for key in keys:
    for vt in val_types:
        print(f"[*] Пробуем: ключ='{key}', тип='{vt}'")
        resp = make_test(key, vt)()
        if resp:
            print(f"\n[!] НАЙДЕН РАБОЧИЙ ФОРМАТ: ключ='{key}', тип='{vt}'")
            found = True
            break
    if found:
        break

if not found:
    print("\n[-] Ничего не сработало.")