import sys
import os

# Try XOR decryption with various keys
def xor_decrypt(data, key):
    key_bytes = key.encode() if isinstance(key, str) else key
    result = bytearray()
    for i, byte in enumerate(data):
        result.append(byte ^ key_bytes[i % len(key_bytes)])
    return bytes(result)

# Read encrypted file
with open('clients_information.xlsx.enc', 'rb') as f:
    encrypted = f.read()

print(f"Encrypted file size: {len(encrypted)} bytes")
print(f"First 16 bytes (hex): {encrypted[:16].hex()}")

# XLSX files start with PK\x03\x04 (ZIP header)
xlsx_header = b'PK\x03\x04'

# Try to brute force XOR key by checking against known header
for key_len in range(1, 32):
    # Calculate what the XOR key would be if the first bytes decrypt to 'PK\x03\x04'
    potential_key = bytearray()
    for i in range(min(key_len, len(xlsx_header))):
        potential_key.append(encrypted[i] ^ xlsx_header[i % len(xlsx_header)])
    
    # Try this key
    decrypted = xor_decrypt(encrypted, bytes(potential_key))
    
    # Check if we got the PK header
    if decrypted[:4] == xlsx_header:
        key_str = bytes(potential_key).decode('ascii', errors='ignore')
        print(f"\n*** FOUND KEY (length {key_len}): {key_str}")
        print(f"Key (hex): {bytes(potential_key).hex()}")
        
        # Save decrypted file
        with open('clients_information.xlsx', 'wb') as f:
            f.write(decrypted)
        print("File decrypted successfully!")
        
        # Try to extract flag from the Excel file 
        try:
            import zipfile
            with zipfile.ZipFile('clients_information.xlsx', 'r') as zip_ref:
                # List all files
                print("\nFiles in XLSX:")
                for name in zip_ref.namelist():
                    print(f"  {name}")
                    # Read content to look for flag
                    content = zip_ref.read(name)
                    if b'HTB{' in content or b'FLAG{' in content or b'flag{' in content:
                        print(f"\n*** FLAG FOUND in {name}:")
                        # Extract the flag
                        import re
                        matches = re.findall(rb'[Hh][Tt][Bb]\{[^}]+\}|[Ff][Ll][Aa][Gg]\{[^}]+\}', content)
                        for match in matches:
                            print(match.decode())
        except Exception as e:
            print(f"Could not extract XLSX contents: {e}")
            # Try reading as text anyway
            print("\nSearching decrypted file for flag...")
            if b'HTB{' in decrypted:
                import re
                matches = re.findall(rb'HTB\{[^}]+\}', decrypted)
                for match in matches:
                    print(f"Found: {match.decode()}")
        
        sys.exit(0)

print("\nKey not found with simple XOR brute force.")
print("Trying common keys manually...")

# Try some common keys based on what we saw in memory
common_keys = [
    '20yk',
    '20ykHw',  
    'infected',
    'secret',
    'key',
    'password'
]

for key in common_keys:
    decrypted = xor_decrypt(encrypted, key)
    if decrypted[:2] == b'PK':
        print(f"\nFound with key: {key}")
        with open('clients_information.xlsx', 'wb') as f:
            f.write(decrypted)
        sys.exit(0)

print("No key found.")
