#!/usr/bin/env python3
"""
Find MIFARE AUTH commands (0x60 or 0x61) and extract the 6-byte keys
"""
import csv

print("[*] Searching for MIFARE AUTH commands in SPI capture...\n")

with open('export.csv', 'r') as f:
    reader = list(csv.DictReader(f))

auth_count = 0

for i in range(len(reader) - 20):
    row = reader[i]
    
    # Look for AUTH command in MOSI (0x60 = AUTHENT1A, 0x61 = AUTHENT1B)
    if row['type'] == 'result' and row['mosi'] in ['0x60', '0x61']:
        auth_cmd = row['mosi']
        
        # Get next bytes: [BLOCK] [KEY 6 bytes] [UID 4 bytes]
        mosi_bytes = []
        for j in range(i, min(i+15, len(reader))):
            r = reader[j]
            if r['type'] == 'result' and r['mosi'] and r['mosi'].startswith('0x'):
                mosi_bytes.append(int(r['mosi'], 16))
        
        if len(mosi_bytes) >= 11:  # CMD + BLOCK + 6 KEY + 4 UID
            auth_count += 1
            
            block = mosi_bytes[1] if len(mosi_bytes) > 1 else 0
            key_bytes = mosi_bytes[2:8] if len(mosi_bytes) >= 8 else []
            uid_bytes = mosi_bytes[8:12] if len(mosi_bytes) >= 12 else []
            
            key_hex = ''.join(f'{b:02x}' for b in key_bytes)
            uid_hex = ''.join(f'{b:02x}' for b in uid_bytes)
            
            print(f"AUTH #{auth_count} at line {i}:")
            print(f"  Command: {auth_cmd}")
            print(f"  Block:   {block} (0x{block:02x})")
            print(f"  Key:     {key_hex} ← THE LCG OUTPUT!")
            print(f"  UID:     {uid_hex}")
            print()
            
            if auth_count >= 6:  # Show first 6 auth attempts
                break

if auth_count > 0:
    print(f"{'='*70}")
    print(f"Found {auth_count} authentication attempts!")
    print(f"These 6-byte keys are the LCG outputs that get appended to auth_code.")
    print(f"{'='*70}")
else:
    print("[-] No AUTH commands found. Let me search more broadly...")
    
    # Try searching for 0x60/0x61 as individual bytes
    print("\n[*] Searching for 0x60 or 0x61 in MOSI stream...")
    for i in range(min(1000, len(reader))):
        row = reader[i]
        if row['type'] == 'result' and row['mosi']:
            if '0x60' in row['mosi'] or '0x61' in row['mosi']:
                print(f"  Line {i}: MOSI={row['mosi']}, MISO={row['miso']}")
