#!/usr/bin/env python3
"""
Layer 2 Decryption - Analyze and decrypt second layer
"""

import base64
import json
from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad

# المفاتيح المحتملة
KEYS = {
    'key1': b'EsySxALGhVMgDldp',
    'key2': b'Al4mK7AwxtYS1yC7',
}

def analyze_binary_data(data):
    """تحليل البيانات الثنائية"""

    print(f"📏 حجم البيانات: {len(data)} bytes")
    print(f"🔢 أول 16 بايت (Hex): {data[:16].hex()}")
    print(f"🔢 آخر 16 بايت (Hex): {data[-16:].hex()}")

    # فحص إذا كان حجم البيانات يتوافق مع AES (مضاعفات 16)
    if len(data) % 16 == 0:
        print("✅ حجم البيانات مضاعف 16 (محتمل AES)")
    else:
        print(f"⚠️  حجم البيانات: {len(data)} (غير مضاعف 16)")

    # فحص entropy (العشوائية)
    unique_bytes = len(set(data))
    entropy = unique_bytes / 256.0
    print(f"📊 Entropy: {entropy:.2%} ({unique_bytes}/256 بايت مختلف)")

    if entropy > 0.9:
        print("   → بيانات عشوائية عالية (محتمل مشفرة)")
    elif entropy > 0.6:
        print("   → بيانات متنوعة (محتمل مضغوطة)")
    else:
        print("   → بيانات منخفضة التنوع")

def try_decrypt_aes(data, key, iv=None):
    """محاولة فك تشفير AES"""
    try:
        if iv is None and len(data) >= 16:
            iv = data[:16]
            ciphertext = data[16:]
        else:
            ciphertext = data
            if iv is None:
                iv = b'\x00' * 16

        cipher = AES.new(key, AES.MODE_CBC, iv)
        decrypted = unpad(cipher.decrypt(ciphertext), AES.block_size)
        return decrypted.decode('utf-8', errors='ignore')
    except:
        return None

def analyze_all_items():
    """تحليل جميع العناصر المفكوكة"""

    print("=" * 80)
    print("🔍 تحليل الطبقة الثانية من التشفير")
    print("=" * 80)

    # قراءة الملف المفكوك
    with open('/var/www/html/encrypted_data_decrypted.json', 'r') as f:
        data = json.load(f)

    print(f"\n📊 إجمالي العناصر: {len(data)}")

    # تحليل أول 5 عناصر
    sizes = []

    for i, item in enumerate(data[:10], 1):
        if not item.get('success'):
            continue

        print(f"\n{'─' * 80}")
        print(f"[عنصر {i}]")

        decrypted_layer1 = item['decrypted']

        try:
            # فك Base64
            binary_data = base64.b64decode(decrypted_layer1)
            sizes.append(len(binary_data))

            print(f"✅ تم فك Base64")
            analyze_binary_data(binary_data)

            # محاولة فك التشفير بجميع المفاتيح
            print("\n🔐 محاولة فك التشفير...")

            found = False
            for key_name, key in KEYS.items():
                # مع IV من البيانات
                result = try_decrypt_aes(binary_data, key, iv=None)
                if result and len(result) > 10:
                    print(f"   ✅ نجح مع {key_name} (IV من البيانات)")
                    print(f"   📝 النتيجة: {result[:100]}...")
                    found = True
                    break

                # مع IV صفري
                result = try_decrypt_aes(binary_data, key, iv=b'\x00' * 16)
                if result and len(result) > 10:
                    print(f"   ✅ نجح مع {key_name} (IV صفري)")
                    print(f"   📝 النتيجة: {result[:100]}...")
                    found = True
                    break

            if not found:
                print("   ❌ لم ينجح فك التشفير مع أي مفتاح")

                # محاولة فك ضغط
                try:
                    import zlib
                    decompressed = zlib.decompress(binary_data)
                    print(f"   ✅ تم فك الضغط (zlib)!")
                    print(f"   📝 النتيجة: {decompressed[:100]}")
                except:
                    pass

                try:
                    import gzip
                    decompressed = gzip.decompress(binary_data)
                    print(f"   ✅ تم فك الضغط (gzip)!")
                    print(f"   📝 النتيجة: {decompressed[:100]}")
                except:
                    pass

        except Exception as e:
            print(f"❌ خطأ: {e}")

    print("\n" + "=" * 80)
    print("📊 إحصائيات أحجام البيانات:")
    if sizes:
        print(f"   الحد الأدنى: {min(sizes)} bytes")
        print(f"   الحد الأقصى: {max(sizes)} bytes")
        print(f"   المتوسط: {sum(sizes)//len(sizes)} bytes")

        # فحص إذا كانت الأحجام متطابقة
        if len(set(sizes)) == 1:
            print(f"   ⚠️  جميع العناصر لها نفس الحجم: {sizes[0]} bytes")

if __name__ == "__main__":
    analyze_all_items()
