#!/usr/bin/env python3
"""
Search for 6-byte sequences in MOSI that could be LCG keys
Each LCG output is 3 bytes (result % 0xffffff)
So we're looking for patterns like: XX XX XX YY YY YY
"""
import csv

print("[*] Searching for 6-byte key patterns in MOSI...\n")

with open('export.csv', 'r') as f:
    reader = list(csv.DictReader(f))

# Extract all MOSI bytes
mosi_bytes = []
for row in reader:
    if row['type'] == 'result' and row['mosi'] and row['mosi'].startswith('0x'):
        mosi_bytes.append(int(row['mosi'], 16))

print(f"[+] Extracted {len(mosi_bytes)} MOSI bytes\n")

# Look for interesting 6-byte sequences
# Filter out common padding/status bytes
interesting_sequences = []

for i in range(len(mosi_bytes) - 5):
    seq = mosi_bytes[i:i+6]
    
    # Check if this could be LCG output (2 × 3-byte values)
    val1 = (seq[0] << 16) | (seq[1] << 8) | seq[2]
    val2 = (seq[3] << 16) | (seq[4] << 8) | seq[5]
    
    # LCG outputs should be < 0xFFFFFF and likely not all zeros/FFs
    if val1 < 0xFFFFFF and val2 < 0xFFFFFF:
        if val1 > 0x100000 and val2 > 0x100000:  # Not too small
            if 0x000000 < val1 < 0xFFFFFF and 0x000000 < val2 < 0xFFFFFF:
                hex_str = ''.join(f'{b:02x}' for b in seq)
                interesting_sequences.append((i, hex_str, val1, val2))

print(f"[+] Found {len(interesting_sequences)} potential 6-byte key sequences\n")

# Show first 20
for idx, (offset, hex_str, v1, v2) in enumerate(interesting_sequences[:20]):
    print(f"Offset {offset:06d}: {hex_str} -> [{v1:06x}, {v2:06x}]")

# Also look for our known sector patterns
print("\n[*] Searching for known sector patterns...")
search_patterns = [
    'cd335e314d4f',  # First 6 bytes of sector 22
    '5e4ce0a70307',  # First 6 bytes of sector 34
]

for pattern in search_patterns:
    # Convert to bytes for searching
    pattern_bytes = bytes.fromhex(pattern)
    found = False
    
    for i in range(len(mosi_bytes) - len(pattern_bytes)):
        if mosi_bytes[i:i+len(pattern_bytes)] == list(pattern_bytes):
            print(f"  Found '{pattern}' at MOSI offset {i}")
            found = True
            break
    
    if not found:
        print(f"  '{pattern}' not found in MOSI")
