ChainFinder: Exploring Cryptographic Algorithm Combinations

Тема в разделе "WASM.CRYPTO", создана пользователем galenkane, 6 июн 2025.

  1. galenkane

    galenkane Active Member

    Публикаций:
    0
    Регистрация:
    13 янв 2017
    Сообщения:
    392
    ChainFinder: Инструмент для исследования криптографических алгоритмов
    Привет всем! Хочу поделиться небольшим, но полезным Python-скриптом, который я назвал ChainFinder. Этот инструмент предназначен для генерации и отображения всех возможных комбинаций криптографических алгоритмов из предопределенных категорий. Это может быть полезно для аналитиков, исследователей или студентов, изучающих криптографические протоколы и желающих увидеть, как различные компоненты могут сочетаться.
    Что делает скрипт?
    Скрипт ChainFinder.py берет набор категорий криптографических функций (таких как обмен ключами, цифровая подпись, симметричное шифрование, хеш-функции и функции вывода ключа) и списки алгоритмов для каждой из них. Затем он генерирует каждую уникальную комбинацию, выбирая по одному алгоритму из каждой категории.
    Основные особенности:
    • Гибкая структура: Легко добавлять новые категории или алгоритмы в существующие.
    • Генерация комбинаций: Использует itertools.product для эффективной генерации всех уникальных сочетаний.
    • Очистка дубликатов: Автоматически удаляет любые дубликаты алгоритмов внутри каждой категории, гарантируя, что каждая комбинация будет уникальной.
    • Понятный вывод: Каждая комбинация отображается с указанием категории и выбранного алгоритма, а также общим количеством найденных комбинаций.
    Как это работает (немного о коде):
    В основе скрипта лежит словарь algorithm_categories, где каждый ключ — это название категории, а значение — список алгоритмов, относящихся к этой категории.
    Код (Text):
    1.  
    2. algorithm_categories = {
    3.     "Key Exchange": [
    4.         "X448 (Curve448/Goldilocks)",
    5.         "X25519 (Curve25519)",
    6.         "ECDH (P-521)",
    7.         "Kyber",
    8.         "NTRU",
    9.         "CECPQ2",
    10.         "SIDH",
    11.         "Crystals-Dilithium (Key Exchange mode)"
    12.     ],
    13.     "Digital Signature": [
    14.         "Ed448 (Edwards-curve Digital Signature Algorithm)",
    15.         "Ed25519 (Edwards-curve Digital Signature Algorithm)",
    16.         "ECDSA (P-521, SHA512)",
    17.         "RSA-PSS (SHA512, MGF1)",
    18.         "Dilithium",
    19.         "Falcon",
    20.         "SPHINCS+",
    21.         "LMS",
    22.         "XMSS"
    23.     ],
    24.     "Symmetric Encryption (AEAD)": [
    25.         "AES-256-GCM",
    26.         "ChaCha20-Poly1305",
    27.         "AES-128-GCM",
    28.         "XChaCha20-Poly1305",
    29.         "Tink-AEAD (Various Modes)",
    30.         "LibreSSL AEAD (Various Modes)",
    31.         "Squirrel-AEAD"
    32.     ],
    33.     "Hash Function": [
    34.         "SHA3-512",
    35.         "SHA2-512",
    36.         "BLAKE2b-512",
    37.         "BLAKE3",
    38.         "SHA3-256",
    39.         "Keccak-512",
    40.         "Ripemd-320",
    41.         "SM3"
    42.     ],
    43.     "Key Derivation Function (KDF)": [
    44.         "HKDF-SHA512",
    45.         "PBKDF2-HMAC-SHA512",
    46.         "Scrypt",
    47.         "Argon2id",
    48.         "PBKDF2-HMAC-SHA256",
    49.         "Bcrypt",
    50.         "bcrypt_pbkdf"
    51.     ]
    52. }
    53.  
    Чтобы обеспечить уникальность алгоритмов внутри каждой категории, мы используем конструкцию list(dict.fromkeys()). Затем itertools.product(*algorithm_lists) генерирует все возможные комбинации.
    Код (Text):
    1.  
    2. import itertools
    3. # ... (algorithm_categories definition) ...
    4. category_names = list(algorithm_categories.keys())
    5. algorithm_lists = list(algorithm_categories.values())
    6. all_combinations = list(itertools.product(*algorithm_lists))
    7. print(f"Total unique algorithm combinations found: {len(all_combinations)}\\n")
    8. for i, combo in enumerate(all_combinations):
    9.     print(f"Combination {i + 1}:")
    10.     for j, category in enumerate(category_names):
    11.         print(f"  {category}: {combo[j]}")
    12.     print("\\n" + "-" * 50 + "\\n")
    13.  
    Как запустить?
    1. Сохраните код как ChainFinder.py.
    2. Откройте терминал или командную строку.
    3. Перейдите в директорию, где вы сохранили файл:
    Код (Text):
    1.  
    2.     cd /путь/к/вашему/файлу
    3.    
    4. Запустите скрипт с помощью Python:
    Код (Text):
    1.  
    2.     python ChainFinder.py
    3.    
    Скрипт выведет в консоль все сгенерированные комбинации, а также общее их количество.
    Надеюсь, этот инструмент будет полезен! Буду рад услышать ваши отзывы и предложения по улучшению.

    Код (Text):
    1. import itertools
    2.  
    3. print("--- ChainFinder: Exploring Cryptographic Algorithm Combinations ---")
    4.  
    5. # Define categories of cryptographic functions and suitable algorithms for each
    6. algorithm_categories = {
    7.     "Key Exchange": list(dict.fromkeys([
    8.         "X448 (Curve448/Goldilocks)",
    9.         "X25519 (Curve25519)",
    10.         "ECDH (P-521)", # Placeholder for elliptic curve Diffie-Hellman
    11.         "Kyber",
    12.         "NTRU",
    13.         "CECPQ2",
    14.         "SIDH",
    15.         "Crystals-Dilithium (Key Exchange mode)"
    16.     ])),
    17.     "Digital Signature": list(dict.fromkeys([
    18.         "Ed448 (Edwards-curve Digital Signature Algorithm)",
    19.         "Ed25519 (Edwards-curve Digital Signature Algorithm)",
    20.         "ECDSA (P-521, SHA512)", # Placeholder for elliptic curve Digital Signature Algorithm
    21.         "RSA-PSS (SHA512, MGF1)", # RSA Probabilistic Signature Scheme
    22.         "Dilithium",
    23.         "Falcon",
    24.         "SPHINCS+",
    25.         "LMS",
    26.         "XMSS"
    27.     ])),
    28.     "Symmetric Encryption (AEAD)": list(dict.fromkeys([
    29.         "AES-256-GCM", # Authenticated Encryption with Associated Data
    30.         "ChaCha20-Poly1305", # Authenticated Encryption with Associated Data
    31.         "AES-128-GCM",
    32.         "XChaCha20-Poly1305",
    33.         "Tink-AEAD (Various Modes)",
    34.         "LibreSSL AEAD (Various Modes)",
    35.         "Squirrel-AEAD"
    36.     ])),
    37.     "Hash Function": list(dict.fromkeys([
    38.         "SHA3-512",
    39.         "SHA2-512",
    40.         "BLAKE2b-512",
    41.         "BLAKE3",
    42.         "SHA3-256",
    43.         "Keccak-512",
    44.         "Ripemd-320",
    45.         "SM3"
    46.     ])),
    47.     "Key Derivation Function (KDF)": list(dict.fromkeys([
    48.         "HKDF-SHA512", # HMAC-based Key Derivation Function
    49.         "PBKDF2-HMAC-SHA512", # Password-Based Key Derivation Function 2
    50.         "Scrypt",
    51.         "Argon2id",
    52.         "PBKDF2-HMAC-SHA256",
    53.         "Bcrypt",
    54.         "bcrypt_pbkdf"
    55.     ]))
    56. }
    57.  
    58. # Generate all combinations of algorithms
    59. # The order of categories will determine the order in the output chains
    60. category_names = list(algorithm_categories.keys())
    61. algorithm_lists = list(algorithm_categories.values())
    62.  
    63. all_combinations = list(itertools.product(*algorithm_lists))
    64.  
    65. print(f"Total unique algorithm combinations found: {len(all_combinations)}\n")
    66.  
    67. # Print each combination
    68. for i, combo in enumerate(all_combinations):
    69.     print(f"Combination {i + 1}:")
    70.     for j, category in enumerate(category_names):
    71.         print(f"  {category}: {combo[j]}")
    72.     print("\n" + "-" * 50 + "\n")
    73.  
    74. print("--- ChainFinder: End of Combinations ---")
    28218 комбинаций сделает =)
     
  2. Research

    Research Active Member

    Публикаций:
    1
    Регистрация:
    6 янв 2024
    Сообщения:
    259
    По-моему технологии вышли из подчинения людей, и развиваются самостоятельно, используя людей в качестве подопытных обезьянок, переносчиков своей заразы )
     
  3. galenkane

    galenkane Active Member

    Публикаций:
    0
    Регистрация:
    13 янв 2017
    Сообщения:
    392
    вы негативный парень кокой-то
     
  4. Prober

    Prober Member

    Публикаций:
    0
    Регистрация:
    4 дек 2008
    Сообщения:
    51
    А должен сделать 8*9*7*8*7 = 28224, нет?
     
  5. galenkane

    galenkane Active Member

    Публикаций:
    0
    Регистрация:
    13 янв 2017
    Сообщения:
    392
    мб дубли удалил
     
  6. galenkane

    galenkane Active Member

    Публикаций:
    0
    Регистрация:
    13 янв 2017
    Сообщения:
    392
    Update
    Total unique algorithm combinations: 15,759,360
    Код (Text):
    1.  
    2. package main
    3. import (
    4.     "bufio"
    5.     "crypto/sha256"
    6.     "encoding/csv"
    7.     "encoding/hex"
    8.     "encoding/json"
    9.     "fmt"
    10.     "os"
    11.     "sort"
    12.     "strings"
    13.     "time"
    14. )
    15.  
    16. type AlgorithmCategory struct {
    17.     Algorithms   []string `json:"algorithms"`
    18.     QuantumSafe  []string `json:"quantum_safe"`
    19.     Performance  string   `json:"performance"`
    20. }
    21.  
    22. var algorithmCategories = map[string]AlgorithmCategory{
    23.     "Key Exchange": {
    24.         Algorithms: []string{
    25.             "X448 (Curve448/Goldilocks)",
    26.             "X25519 (Curve25519)",
    27.             "ECDH (P-521)",
    28.             "ECDH (P-384)",
    29.             "ECDH (secp256k1)",
    30.             "Kyber-1024 (NIST Level 5)",
    31.             "Kyber-768 (NIST Level 3)",
    32.             "Kyber-512 (NIST Level 1)",
    33.             "NTRU-HRSS-701",
    34.             "NTRU-HPS-4096-821",
    35.             "CECPQ2 (X25519 + NTRU-HRSS)",
    36.             "SIDH (P-751)",
    37.             "SIKE (P-434)",         "Crystals-Dilithium (Key Exchange mode)",
    38.             "FrodoKEM-1344-AES",
    39.             "BIKE (Round 4)",
    40.             "Classic McEliece (348864)",
    41.             "HQC-256",
    42.         },
    43.         QuantumSafe: []string{
    44.             "Kyber-1024", "Kyber-768", "Kyber-512", "NTRU-HRSS-701",
    45.             "NTRU-HPS-4096-821", "FrodoKEM-1344-AES", "BIKE", "Classic McEliece", "HQC-256",
    46.         },
    47.         Performance: "high_impact",
    48.     },
    49.     "Digital Signature": {
    50.         Algorithms: []string{
    51.             "Ed448 (Edwards-curve)",
    52.             "Ed25519 (Edwards-curve)",
    53.             "ECDSA (P-521, SHA-512)",
    54.             "ECDSA (P-384, SHA-384)",
    55.             "ECDSA (P-256, SHA-256)",
    56.             "RSA-PSS (4096-bit, SHA-512, MGF1)",
    57.             "RSA-PSS (3072-bit, SHA-256, MGF1)",
    58.             "Dilithium-5 (NIST Level 5)",
    59.             "Dilithium-3 (NIST Level 3)",
    60.             "Dilithium-2 (NIST Level 1)",
    61.             "Falcon-1024",
    62.             "Falcon-512",
    63.             "SPHINCS+-256s (SHA-256)",
    64.             "SPHINCS+-256f (SHA-256)",
    65.             "SPHINCS+-SHAKE-256s",
    66.             "LMS (HSS with SHA-256/192)",
    67.             "XMSS (SHA-256, h=20)",
    68.             "PICNIC3-L5",
    69.             "Rainbow-V-Classic",
    70.         },
    71.         QuantumSafe: []string{
    72.             "Dilithium-5", "Dilithium-3", "Dilithium-2", "Falcon-1024",
    73.             "Falcon-512", "SPHINCS+", "LMS", "XMSS", "PICNIC3-L5",
    74.         },
    75.         Performance: "medium_impact",
    76.     },
    77.     "Symmetric Encryption (AEAD)": {
    78.         Algorithms: []string{
    79.             "AES-256-GCM",
    80.             "AES-192-GCM",
    81.             "AES-128-GCM",
    82.             "ChaCha20-Poly1305",
    83.             "XChaCha20-Poly1305",
    84.             "AES-256-OCB3",
    85.             "AES-128-OCB3",
    86.             "AES-256-SIV",
    87.             "Deoxys-II-256-128",
    88.             "AEGIS-256",
    89.             "AEGIS-128",
    90.             "Ascon-128a",
    91.             "Ascon-128",
    92.             "COLM-128",
    93.             "Tink-AEAD (AES-GCM)",
    94.             "Tink-AEAD (ChaCha20-Poly1305)",
    95.         },
    96.         QuantumSafe: []string{},
    97.         Performance: "low_impact",
    98.     },
    99.     "Hash Function": {
    100.         Algorithms: []string{
    101.             "SHA3-512 (Keccak)",
    102.             "SHA3-384 (Keccak)",
    103.             "SHA3-256 (Keccak)",
    104.             "SHA2-512",
    105.             "SHA2-384",
    106.             "SHA2-256",
    107.             "BLAKE3 (256-bit)",
    108.             "BLAKE2b-512",
    109.             "BLAKE2b-256",
    110.             "BLAKE2s-256",
    111.             "Keccak-512",
    112.             "Keccak-256",
    113.             "SHAKE256 (Extendable)",
    114.             "SHAKE128 (Extendable)",
    115.             "Whirlpool-512",
    116.             "SM3-256 (Chinese Standard)",
    117.             "Streebog-512 (GOST R 34.11-2012)",
    118.             "Skein-512-512",
    119.         },
    120.         QuantumSafe: []string{},
    121.         Performance: "low_impact",
    122.     },
    123.     "Key Derivation Function (KDF)": {
    124.         Algorithms: []string{
    125.             "HKDF-SHA3-512",
    126.             "HKDF-SHA2-512",
    127.             "HKDF-BLAKE3",
    128.             "PBKDF2-HMAC-SHA3-512",
    129.             "PBKDF2-HMAC-SHA2-512",
    130.             "PBKDF2-HMAC-SHA2-256",
    131.             "Scrypt (N=2^20, r=8, p=1)",
    132.             "Scrypt (N=2^17, r=8, p=1)",
    133.             "Argon2id (m=2^19, t=2, p=1)",
    134.             "Argon2id (m=2^16, t=3, p=1)",
    135.             "Argon2i (Memory-hard)",
    136.             "Argon2d (Data-dependent)",
    137.             "Bcrypt (cost=12)",
    138.             "bcrypt_pbkdf",
    139.             "Balloon Hashing",
    140.             "Catena-Dragonfly",
    141.         },
    142.         QuantumSafe: []string{},
    143.         Performance: "high_impact",
    144.     },
    145.     "Message Authentication Code (MAC)": {
    146.         Algorithms: []string{
    147.             "HMAC-SHA3-512",
    148.             "HMAC-SHA2-512",
    149.             "HMAC-BLAKE3",
    150.             "KMAC256 (Keccak-based)",
    151.             "KMAC128 (Keccak-based)",
    152.             "Poly1305 (with ChaCha20)",
    153.             "SipHash-2-4",
    154.             "BLAKE2b-MAC",
    155.             "GMAC (GCM mode)",
    156.             "CMAC-AES-256",
    157.         },
    158.         QuantumSafe: []string{},
    159.         Performance: "low_impact",
    160.     },
    161. }
    162.  
    163. var securityLevels = map[string][]string{
    164.     "Post-Quantum":      {"Kyber", "Dilithium", "Falcon", "SPHINCS+", "NTRU", "FrodoKEM", "BIKE", "Classic McEliece", "HQC"},
    165.     "Classical-High":    {"X448", "Ed448", "P-521", "RSA-4096", "AES-256", "SHA3-512", "BLAKE3"},
    166.     "Classical-Standard": {"X25519", "Ed25519", "P-384", "P-256", "RSA-3072", "AES-128", "SHA2-256"},
    167.     "Hybrid-Ready":      {"CECPQ2", "X25519+Kyber", "P-384+Dilithium"},
    168. }
    169.  
    170. var performanceProfiles = map[string][]string{
    171.     "High-Performance": {"X25519", "Ed25519", "ChaCha20-Poly1305", "BLAKE3", "AES-GCM"},
    172.     "Balanced":         {"P-384", "ECDSA-P384", "AES-256-GCM", "SHA3-256", "Argon2id"},
    173.     "High-Security":    {"X448", "Ed448", "Kyber-1024", "Dilithium-5", "SHA3-512"},
    174. }
    175.  
    176. func init() {
    177.     // Symmetric crypto generally quantum-resistant with doubled key sizes
    178.     ae := algorithmCategories["Symmetric Encryption (AEAD)"]
    179.     ae.QuantumSafe = ae.Algorithms
    180.     algorithmCategories["Symmetric Encryption (AEAD)"] = ae
    181.  
    182.     hf := algorithmCategories["Hash Function"]
    183.     hf.QuantumSafe = hf.Algorithms
    184.     algorithmCategories["Hash Function"] = hf
    185.  
    186.     kdf := algorithmCategories["Key Derivation Function (KDF)"]
    187.     kdf.QuantumSafe = kdf.Algorithms
    188.     algorithmCategories["Key Derivation Function (KDF)"] = kdf
    189.  
    190.     mac := algorithmCategories["Message Authentication Code (MAC)"]
    191.     mac.QuantumSafe = mac.Algorithms
    192.     algorithmCategories["Message Authentication Code (MAC)"] = mac
    193. }
    194.  
    195. type ComboScore struct {
    196.     QuantumResistance int `json:"quantum_resistance"`
    197.     ClassicalSecurity int `json:"classical_security"`
    198.     Performance       int `json:"performance"`
    199.     Total             int `json:"total"`
    200. }
    201.  
    202. func calculateCombinationScore(combo []string, categoryNames []string) ComboScore {
    203.     score := ComboScore{}
    204.  
    205.     for i, alg := range combo {
    206.         category := categoryNames[i]
    207.  
    208.         // Quantum resistance scoring
    209.         for _, qrAlg := range algorithmCategories[category].QuantumSafe {
    210.             if contains(alg, qrAlg) {
    211.                 score.QuantumResistance += 20
    212.                 break
    213.             }
    214.         }
    215.  
    216.         // Classical security scoring
    217.         for _, csAlg := range securityLevels["Classical-High"] {
    218.             if contains(alg, csAlg) {
    219.                 score.ClassicalSecurity += 15
    220.                 break
    221.             }
    222.         }
    223.  
    224.         for _, csAlg := range securityLevels["Classical-Standard"] {
    225.             if contains(alg, csAlg) {
    226.                 score.ClassicalSecurity += 10
    227.                 break
    228.             }
    229.         }
    230.  
    231.         // Performance scoring (inverse - higher numbers = worse performance)
    232.         perfImpact := algorithmCategories[category].Performance
    233.         if perfImpact == "low_impact" {
    234.             score.Performance += 10
    235.         } else if perfImpact == "medium_impact" {
    236.             score.Performance += 5
    237.         }
    238.     }
    239.  
    240.     score.Total = score.QuantumResistance + score.ClassicalSecurity + score.Performance
    241.     return score
    242. }
    243.  
    244. func contains(s string, substr string) bool {
    245.     return len(s) >= len(substr) && s[0:len(substr)] == substr
    246. }
    247.  
    248. type CategorizedCombination struct {
    249.     Combination []string
    250.     Score       ComboScore
    251. }
    252.  
    253. func categorizeCombinations(combinations [][]string, categoryNames []string) map[string][]CategorizedCombination {
    254.     categorized := map[string][]CategorizedCombination{
    255.         "quantum_ready":    {},
    256.         "hybrid_classical": {},
    257.         "high_performance": {},
    258.         "maximum_security": {},
    259.         "balanced":         {},
    260.     }
    261.  
    262.     for _, combo := range combinations {
    263.         score := calculateCombinationScore(combo, categoryNames)
    264.         catCombo := CategorizedCombination{Combination: combo, Score: score}
    265.  
    266.         if score.QuantumResistance >= 100 {
    267.             categorized["quantum_ready"] = append(categorized["quantum_ready"], catCombo)
    268.         }
    269.         if score.QuantumResistance >= 40 {
    270.             categorized["hybrid_classical"] = append(categorized["hybrid_classical"], catCombo)
    271.         }
    272.  
    273.         if score.Performance >= 50 {
    274.             categorized["high_performance"] = append(categorized["high_performance"], catCombo)
    275.         }
    276.  
    277.         if score.ClassicalSecurity >= 75 {
    278.             categorized["maximum_security"] = append(categorized["maximum_security"], catCombo)
    279.         }
    280.  
    281.         if score.Total >= 40 && score.Total <= 80 {
    282.             categorized["balanced"] = append(categorized["balanced"], catCombo)
    283.         }
    284.     }
    285.  
    286.     return categorized
    287. }
    288.  
    289. func generateCombinationHash(combo []string) string {
    290.     comboStr := strings.Join(combo, "|")
    291.     hash := sha256.Sum256([]byte(comboStr))
    292.     return hex.EncodeToString(hash[:])[:12]
    293. }
    294.  
    295. func generateCombinations(lists [][]string) [][]string {
    296.     if len(lists) == 0 {
    297.         return [][]string{{}}
    298.     }
    299.  
    300.     firstList := lists[0]
    301.     restOfLists := lists[1:]
    302.  
    303.     restCombinations := generateCombinations(restOfLists)
    304.  
    305.     var result [][]string
    306.     for _, item := range firstList {
    307.         for _, combo := range restCombinations {
    308.             newCombo := append([]string{item}, combo...)
    309.             result = append(result, newCombo)
    310.         }
    311.     }
    312.  
    313.     return result
    314. }
    315.  
    316. func main() {
    317.     fmt.Println("=== CryptoChainForge: Advanced Cryptographic Algorithm Suite Generator ===")
    318.     fmt.Printf("Generated on: %s\n\n", time.Now().Format("2006-01-02 15:04:05"))
    319.  
    320.     // Generate all combinations
    321.     var categoryNames []string
    322.     for cat := range algorithmCategories {
    323.         categoryNames = append(categoryNames, cat)
    324.     }
    325.  
    326.     // Sort categoryNames for consistent iteration (optional, but good practice)
    327.     // This assumes the order of categories matters for category_names[i] in calculateCombinationScore
    328.     // If the order doesn't matter, this sort can be removed.
    329.     // For now, I'll keep the order as in the Python script's iteration over keys.
    330.  
    331.     var algorithmLists = make([][]string, len(categoryNames))
    332.     for i, cat := range categoryNames {
    333.         algorithmLists[i] = algorithmCategories[cat].Algorithms
    334.     }
    335.  
    336.     fmt.Printf("Generating combinations from %d categories:\n", len(categoryNames))
    337.     for i, cat := range categoryNames {
    338.         fmt.Printf("  %d. %s: %d algorithms\n", i+1, cat, len(algorithmLists[i]))
    339.     }
    340.  
    341.     allCombinations := generateCombinations(algorithmLists)
    342.     fmt.Printf("\nTotal unique algorithm combinations: %d\n", len(allCombinations))
    343.  
    344.     // Categorize combinations
    345.     fmt.Println("\nAnalyzing combinations...")
    346.     categorizedCombos := categorizeCombinations(allCombinations, categoryNames)
    347.  
    348.     // Display summary statistics
    349.     fmt.Printf("\n%s\n", strings.Repeat("=", 60))
    350.     fmt.Println("COMBINATION ANALYSIS SUMMARY")
    351.     fmt.Printf("%s\n", strings.Repeat("=", 60))
    352.  
    353.     for category, combos := range categorizedCombos {
    354.         fmt.Printf("%s: %d combinations\n", strings.ReplaceAll(strings.Title(strings.ReplaceAll(category, "_", " ")), " ", ""), len(combos))
    355.     }
    356.  
    357.     // Display top recommendations for each category
    358.     fmt.Printf("\n%s\n", strings.Repeat("=", 60))
    359.     fmt.Println("TOP RECOMMENDED COMBINATIONS")
    360.     fmt.Printf("%s\n", strings.Repeat("=", 60))
    361.  
    362.     for category, combos := range categorizedCombos {
    363.         if len(combos) == 0 {
    364.             continue
    365.         }
    366.  
    367.         fmt.Printf("\n--- %s ---\n", strings.ToUpper(strings.ReplaceAll(category, "_", " ")))
    368.  
    369.         // Sort by total score and show top 3
    370.         // In Go, we'll use sort.Slice
    371.         sort.Slice(combos, func(i, j int) bool {
    372.             return combos[i].Score.Total > combos[j].Score.Total
    373.         })
    374.  
    375.         top3 := combos
    376.         if len(combos) > 3 {
    377.             top3 = combos[:3]
    378.         }
    379.  
    380.         for idx, catCombo := range top3 {
    381.             comboHash := generateCombinationHash(catCombo.Combination)
    382.             fmt.Printf("\nRecommendation #%d [ID: %s]\n", idx+1, comboHash)
    383.             fmt.Printf("Score: %d (QR: %d, CS: %d, Perf: %d)\n",
    384.                 catCombo.Score.Total, catCombo.Score.QuantumResistance,
    385.                 catCombo.Score.ClassicalSecurity, catCombo.Score.Performance)
    386.  
    387.             for j, categoryName := range categoryNames {
    388.                 fmt.Printf("  %s: %s\n", categoryName, catCombo.Combination[j])
    389.             }
    390.         }
    391.     }
    392.  
    393.     // Generate full detailed output (optional - can be saved to file)
    394.     reader := bufio.NewReader(os.Stdin)
    395.     fmt.Printf("\nGenerate full detailed output of all %d combinations? (y/N): ", len(allCombinations))
    396.     input, _ := reader.ReadString('\n')
    397.     generateFullOutput := strings.TrimSpace(strings.ToLower(input)) == "y"
    398.  
    399.     if generateFullOutput {
    400.         fmt.Printf("\n%s\n", strings.Repeat("=", 80))
    401.         fmt.Println("COMPLETE COMBINATION LISTING")
    402.         fmt.Printf("%s\n", strings.Repeat("=", 80))
    403.  
    404.         for i, combo := range allCombinations {
    405.             score := calculateCombinationScore(combo, categoryNames)
    406.             comboHash := generateCombinationHash(combo)
    407.  
    408.             fmt.Printf("\nCombination %d [ID: %s]\n", i+1, comboHash)
    409.             fmt.Printf("Security Score: %d (Quantum: %d, Classical: %d, Performance: %d)\n",
    410.                 score.Total, score.QuantumResistance, score.ClassicalSecurity, score.Performance)
    411.  
    412.             for j, categoryName := range categoryNames {
    413.                 fmt.Printf("  %s: %s\n", categoryName, combo[j])
    414.             }
    415.  
    416.             if (i+1)%100 == 0 {
    417.                 fmt.Printf("\n--- Processed %d combinations ---\n", i+1)
    418.             }
    419.         }
    420.     }
    421.  
    422.     // Export options
    423.     fmt.Print("\nExport results? (j)son/(c)sv/(n)one: ")
    424.     exportChoiceInput, _ := reader.ReadString('\n')
    425.     exportChoice := strings.TrimSpace(strings.ToLower(exportChoiceInput))
    426.  
    427.     if exportChoice == "j" {
    428.         exportData := map[string]interface{}{
    429.             "metadata": map[string]interface{}{
    430.                 "generated_at":       time.Now().Format(time.RFC3339),
    431.                 "total_combinations": len(allCombinations),
    432.                 "categories":         categoryNames,
    433.             },
    434.             "categorized_results": map[string]interface{}{},
    435.         }
    436.  
    437.         categorizedResultsMap := exportData["categorized_results"].(map[string]interface{})
    438.         for category, combos := range categorizedCombos {
    439.             var comboList []map[string]interface{}
    440.             for _, catCombo := range combos {
    441.                 comboList = append(comboList, map[string]interface{}{
    442.                     "combination": catCombo.Combination,
    443.                     "score":       catCombo.Score,
    444.                     "hash":        generateCombinationHash(catCombo.Combination),
    445.                 })
    446.             }
    447.             categorizedResultsMap[category] = comboList
    448.         }
    449.  
    450.         filename := fmt.Sprintf("crypto_combinations_%s.json", time.Now().Format("20060102_150405"))
    451.         file, err := os.Create(filename)
    452.         if err != nil {
    453.             fmt.Printf("Error creating file: %v\n", err)
    454.             return
    455.         }
    456.         defer file.Close()
    457.  
    458.         encoder := json.NewEncoder(file)
    459.         encoder.SetIndent("", "  ")
    460.         err = encoder.Encode(exportData)
    461.         if err != nil {
    462.             fmt.Printf("Error encoding JSON: %v\n", err)
    463.             return
    464.         }
    465.         fmt.Printf("Results exported to %s\n", filename)
    466.  
    467.     } else if exportChoice == "c" {
    468.         filename := fmt.Sprintf("crypto_combinations_%s.csv", time.Now().Format("20060102_150405"))
    469.         file, err := os.Create(filename)
    470.         if err != nil {
    471.             fmt.Printf("Error creating file: %v\n", err)
    472.             return
    473.         }
    474.         defer file.Close()
    475.  
    476.         writer := csv.NewWriter(file)
    477.  
    478.         // CSV header
    479.         headers := append([]string{"ID", "Category"}, categoryNames...)
    480.         headers = append(headers, "Quantum_Score", "Classical_Score", "Performance_Score", "Total_Score")
    481.         writer.Write(headers)
    482.  
    483.         for category, combos := range categorizedCombos {
    484.             for _, catCombo := range combos {
    485.                 comboHash := generateCombinationHash(catCombo.Combination)
    486.                 row := []string{comboHash, category}
    487.                 row = append(row, catCombo.Combination...)
    488.                 row = append(row, fmt.Sprintf("%d", catCombo.Score.QuantumResistance))
    489.                 row = append(row, fmt.Sprintf("%d", catCombo.Score.ClassicalSecurity))
    490.                 row = append(row, fmt.Sprintf("%d", catCombo.Score.Performance))
    491.                 row = append(row, fmt.Sprintf("%d", catCombo.Score.Total))
    492.                 writer.Write(row)
    493.             }
    494.         }
    495.         writer.Flush()
    496.  
    497.         if err := writer.Error(); err != nil {
    498.             fmt.Printf("Error writing CSV: %v\n", err)
    499.             return
    500.         }
    501.         fmt.Printf("Results exported to %s\n", filename)
    502.     }
    503.  
    504.     fmt.Printf("\n%s\n", strings.Repeat("=", 60))
    505.     fmt.Println("CryptoChainForge: Analysis Complete")
    506.     fmt.Printf("%s\n", strings.Repeat("=", 60))
    507. }
    508.  
    509.