ChainFinder: Инструмент для исследования криптографических алгоритмовПривет всем! Хочу поделиться небольшим, но полезным Python-скриптом, который я назвал ChainFinder. Этот инструмент предназначен для генерации и отображения всех возможных комбинаций криптографических алгоритмов из предопределенных категорий. Это может быть полезно для аналитиков, исследователей или студентов, изучающих криптографические протоколы и желающих увидеть, как различные компоненты могут сочетаться. Что делает скрипт?Скрипт ChainFinder.py берет набор категорий криптографических функций (таких как обмен ключами, цифровая подпись, симметричное шифрование, хеш-функции и функции вывода ключа) и списки алгоритмов для каждой из них. Затем он генерирует каждую уникальную комбинацию, выбирая по одному алгоритму из каждой категории. Основные особенности: Гибкая структура: Легко добавлять новые категории или алгоритмы в существующие. Генерация комбинаций: Использует itertools.product для эффективной генерации всех уникальных сочетаний. Очистка дубликатов: Автоматически удаляет любые дубликаты алгоритмов внутри каждой категории, гарантируя, что каждая комбинация будет уникальной. Понятный вывод: Каждая комбинация отображается с указанием категории и выбранного алгоритма, а также общим количеством найденных комбинаций. Как это работает (немного о коде):В основе скрипта лежит словарь algorithm_categories, где каждый ключ — это название категории, а значение — список алгоритмов, относящихся к этой категории. Код (Text): algorithm_categories = { "Key Exchange": [ "X448 (Curve448/Goldilocks)", "X25519 (Curve25519)", "ECDH (P-521)", "Kyber", "NTRU", "CECPQ2", "SIDH", "Crystals-Dilithium (Key Exchange mode)" ], "Digital Signature": [ "Ed448 (Edwards-curve Digital Signature Algorithm)", "Ed25519 (Edwards-curve Digital Signature Algorithm)", "ECDSA (P-521, SHA512)", "RSA-PSS (SHA512, MGF1)", "Dilithium", "Falcon", "SPHINCS+", "LMS", "XMSS" ], "Symmetric Encryption (AEAD)": [ "AES-256-GCM", "ChaCha20-Poly1305", "AES-128-GCM", "XChaCha20-Poly1305", "Tink-AEAD (Various Modes)", "LibreSSL AEAD (Various Modes)", "Squirrel-AEAD" ], "Hash Function": [ "SHA3-512", "SHA2-512", "BLAKE2b-512", "BLAKE3", "SHA3-256", "Keccak-512", "Ripemd-320", "SM3" ], "Key Derivation Function (KDF)": [ "HKDF-SHA512", "PBKDF2-HMAC-SHA512", "Scrypt", "Argon2id", "PBKDF2-HMAC-SHA256", "Bcrypt", "bcrypt_pbkdf" ] } Чтобы обеспечить уникальность алгоритмов внутри каждой категории, мы используем конструкцию list(dict.fromkeys()). Затем itertools.product(*algorithm_lists) генерирует все возможные комбинации. Код (Text): import itertools # ... (algorithm_categories definition) ... category_names = list(algorithm_categories.keys()) algorithm_lists = list(algorithm_categories.values()) all_combinations = list(itertools.product(*algorithm_lists)) print(f"Total unique algorithm combinations found: {len(all_combinations)}\\n") for i, combo in enumerate(all_combinations): print(f"Combination {i + 1}:") for j, category in enumerate(category_names): print(f" {category}: {combo[j]}") print("\\n" + "-" * 50 + "\\n") Как запустить?1. Сохраните код как ChainFinder.py. 2. Откройте терминал или командную строку. 3. Перейдите в директорию, где вы сохранили файл: Код (Text): cd /путь/к/вашему/файлу 4. Запустите скрипт с помощью Python: Код (Text): python ChainFinder.py Скрипт выведет в консоль все сгенерированные комбинации, а также общее их количество. Надеюсь, этот инструмент будет полезен! Буду рад услышать ваши отзывы и предложения по улучшению. Код (Text): import itertools print("--- ChainFinder: Exploring Cryptographic Algorithm Combinations ---") # Define categories of cryptographic functions and suitable algorithms for each algorithm_categories = { "Key Exchange": list(dict.fromkeys([ "X448 (Curve448/Goldilocks)", "X25519 (Curve25519)", "ECDH (P-521)", # Placeholder for elliptic curve Diffie-Hellman "Kyber", "NTRU", "CECPQ2", "SIDH", "Crystals-Dilithium (Key Exchange mode)" ])), "Digital Signature": list(dict.fromkeys([ "Ed448 (Edwards-curve Digital Signature Algorithm)", "Ed25519 (Edwards-curve Digital Signature Algorithm)", "ECDSA (P-521, SHA512)", # Placeholder for elliptic curve Digital Signature Algorithm "RSA-PSS (SHA512, MGF1)", # RSA Probabilistic Signature Scheme "Dilithium", "Falcon", "SPHINCS+", "LMS", "XMSS" ])), "Symmetric Encryption (AEAD)": list(dict.fromkeys([ "AES-256-GCM", # Authenticated Encryption with Associated Data "ChaCha20-Poly1305", # Authenticated Encryption with Associated Data "AES-128-GCM", "XChaCha20-Poly1305", "Tink-AEAD (Various Modes)", "LibreSSL AEAD (Various Modes)", "Squirrel-AEAD" ])), "Hash Function": list(dict.fromkeys([ "SHA3-512", "SHA2-512", "BLAKE2b-512", "BLAKE3", "SHA3-256", "Keccak-512", "Ripemd-320", "SM3" ])), "Key Derivation Function (KDF)": list(dict.fromkeys([ "HKDF-SHA512", # HMAC-based Key Derivation Function "PBKDF2-HMAC-SHA512", # Password-Based Key Derivation Function 2 "Scrypt", "Argon2id", "PBKDF2-HMAC-SHA256", "Bcrypt", "bcrypt_pbkdf" ])) } # Generate all combinations of algorithms # The order of categories will determine the order in the output chains category_names = list(algorithm_categories.keys()) algorithm_lists = list(algorithm_categories.values()) all_combinations = list(itertools.product(*algorithm_lists)) print(f"Total unique algorithm combinations found: {len(all_combinations)}\n") # Print each combination for i, combo in enumerate(all_combinations): print(f"Combination {i + 1}:") for j, category in enumerate(category_names): print(f" {category}: {combo[j]}") print("\n" + "-" * 50 + "\n") print("--- ChainFinder: End of Combinations ---") 28218 комбинаций сделает =)
По-моему технологии вышли из подчинения людей, и развиваются самостоятельно, используя людей в качестве подопытных обезьянок, переносчиков своей заразы )
Update Total unique algorithm combinations: 15,759,360 Код (Text): package main import ( "bufio" "crypto/sha256" "encoding/csv" "encoding/hex" "encoding/json" "fmt" "os" "sort" "strings" "time" ) type AlgorithmCategory struct { Algorithms []string `json:"algorithms"` QuantumSafe []string `json:"quantum_safe"` Performance string `json:"performance"` } var algorithmCategories = map[string]AlgorithmCategory{ "Key Exchange": { Algorithms: []string{ "X448 (Curve448/Goldilocks)", "X25519 (Curve25519)", "ECDH (P-521)", "ECDH (P-384)", "ECDH (secp256k1)", "Kyber-1024 (NIST Level 5)", "Kyber-768 (NIST Level 3)", "Kyber-512 (NIST Level 1)", "NTRU-HRSS-701", "NTRU-HPS-4096-821", "CECPQ2 (X25519 + NTRU-HRSS)", "SIDH (P-751)", "SIKE (P-434)", "Crystals-Dilithium (Key Exchange mode)", "FrodoKEM-1344-AES", "BIKE (Round 4)", "Classic McEliece (348864)", "HQC-256", }, QuantumSafe: []string{ "Kyber-1024", "Kyber-768", "Kyber-512", "NTRU-HRSS-701", "NTRU-HPS-4096-821", "FrodoKEM-1344-AES", "BIKE", "Classic McEliece", "HQC-256", }, Performance: "high_impact", }, "Digital Signature": { Algorithms: []string{ "Ed448 (Edwards-curve)", "Ed25519 (Edwards-curve)", "ECDSA (P-521, SHA-512)", "ECDSA (P-384, SHA-384)", "ECDSA (P-256, SHA-256)", "RSA-PSS (4096-bit, SHA-512, MGF1)", "RSA-PSS (3072-bit, SHA-256, MGF1)", "Dilithium-5 (NIST Level 5)", "Dilithium-3 (NIST Level 3)", "Dilithium-2 (NIST Level 1)", "Falcon-1024", "Falcon-512", "SPHINCS+-256s (SHA-256)", "SPHINCS+-256f (SHA-256)", "SPHINCS+-SHAKE-256s", "LMS (HSS with SHA-256/192)", "XMSS (SHA-256, h=20)", "PICNIC3-L5", "Rainbow-V-Classic", }, QuantumSafe: []string{ "Dilithium-5", "Dilithium-3", "Dilithium-2", "Falcon-1024", "Falcon-512", "SPHINCS+", "LMS", "XMSS", "PICNIC3-L5", }, Performance: "medium_impact", }, "Symmetric Encryption (AEAD)": { Algorithms: []string{ "AES-256-GCM", "AES-192-GCM", "AES-128-GCM", "ChaCha20-Poly1305", "XChaCha20-Poly1305", "AES-256-OCB3", "AES-128-OCB3", "AES-256-SIV", "Deoxys-II-256-128", "AEGIS-256", "AEGIS-128", "Ascon-128a", "Ascon-128", "COLM-128", "Tink-AEAD (AES-GCM)", "Tink-AEAD (ChaCha20-Poly1305)", }, QuantumSafe: []string{}, Performance: "low_impact", }, "Hash Function": { Algorithms: []string{ "SHA3-512 (Keccak)", "SHA3-384 (Keccak)", "SHA3-256 (Keccak)", "SHA2-512", "SHA2-384", "SHA2-256", "BLAKE3 (256-bit)", "BLAKE2b-512", "BLAKE2b-256", "BLAKE2s-256", "Keccak-512", "Keccak-256", "SHAKE256 (Extendable)", "SHAKE128 (Extendable)", "Whirlpool-512", "SM3-256 (Chinese Standard)", "Streebog-512 (GOST R 34.11-2012)", "Skein-512-512", }, QuantumSafe: []string{}, Performance: "low_impact", }, "Key Derivation Function (KDF)": { Algorithms: []string{ "HKDF-SHA3-512", "HKDF-SHA2-512", "HKDF-BLAKE3", "PBKDF2-HMAC-SHA3-512", "PBKDF2-HMAC-SHA2-512", "PBKDF2-HMAC-SHA2-256", "Scrypt (N=2^20, r=8, p=1)", "Scrypt (N=2^17, r=8, p=1)", "Argon2id (m=2^19, t=2, p=1)", "Argon2id (m=2^16, t=3, p=1)", "Argon2i (Memory-hard)", "Argon2d (Data-dependent)", "Bcrypt (cost=12)", "bcrypt_pbkdf", "Balloon Hashing", "Catena-Dragonfly", }, QuantumSafe: []string{}, Performance: "high_impact", }, "Message Authentication Code (MAC)": { Algorithms: []string{ "HMAC-SHA3-512", "HMAC-SHA2-512", "HMAC-BLAKE3", "KMAC256 (Keccak-based)", "KMAC128 (Keccak-based)", "Poly1305 (with ChaCha20)", "SipHash-2-4", "BLAKE2b-MAC", "GMAC (GCM mode)", "CMAC-AES-256", }, QuantumSafe: []string{}, Performance: "low_impact", }, } var securityLevels = map[string][]string{ "Post-Quantum": {"Kyber", "Dilithium", "Falcon", "SPHINCS+", "NTRU", "FrodoKEM", "BIKE", "Classic McEliece", "HQC"}, "Classical-High": {"X448", "Ed448", "P-521", "RSA-4096", "AES-256", "SHA3-512", "BLAKE3"}, "Classical-Standard": {"X25519", "Ed25519", "P-384", "P-256", "RSA-3072", "AES-128", "SHA2-256"}, "Hybrid-Ready": {"CECPQ2", "X25519+Kyber", "P-384+Dilithium"}, } var performanceProfiles = map[string][]string{ "High-Performance": {"X25519", "Ed25519", "ChaCha20-Poly1305", "BLAKE3", "AES-GCM"}, "Balanced": {"P-384", "ECDSA-P384", "AES-256-GCM", "SHA3-256", "Argon2id"}, "High-Security": {"X448", "Ed448", "Kyber-1024", "Dilithium-5", "SHA3-512"}, } func init() { // Symmetric crypto generally quantum-resistant with doubled key sizes ae := algorithmCategories["Symmetric Encryption (AEAD)"] ae.QuantumSafe = ae.Algorithms algorithmCategories["Symmetric Encryption (AEAD)"] = ae hf := algorithmCategories["Hash Function"] hf.QuantumSafe = hf.Algorithms algorithmCategories["Hash Function"] = hf kdf := algorithmCategories["Key Derivation Function (KDF)"] kdf.QuantumSafe = kdf.Algorithms algorithmCategories["Key Derivation Function (KDF)"] = kdf mac := algorithmCategories["Message Authentication Code (MAC)"] mac.QuantumSafe = mac.Algorithms algorithmCategories["Message Authentication Code (MAC)"] = mac } type ComboScore struct { QuantumResistance int `json:"quantum_resistance"` ClassicalSecurity int `json:"classical_security"` Performance int `json:"performance"` Total int `json:"total"` } func calculateCombinationScore(combo []string, categoryNames []string) ComboScore { score := ComboScore{} for i, alg := range combo { category := categoryNames[i] // Quantum resistance scoring for _, qrAlg := range algorithmCategories[category].QuantumSafe { if contains(alg, qrAlg) { score.QuantumResistance += 20 break } } // Classical security scoring for _, csAlg := range securityLevels["Classical-High"] { if contains(alg, csAlg) { score.ClassicalSecurity += 15 break } } for _, csAlg := range securityLevels["Classical-Standard"] { if contains(alg, csAlg) { score.ClassicalSecurity += 10 break } } // Performance scoring (inverse - higher numbers = worse performance) perfImpact := algorithmCategories[category].Performance if perfImpact == "low_impact" { score.Performance += 10 } else if perfImpact == "medium_impact" { score.Performance += 5 } } score.Total = score.QuantumResistance + score.ClassicalSecurity + score.Performance return score } func contains(s string, substr string) bool { return len(s) >= len(substr) && s[0:len(substr)] == substr } type CategorizedCombination struct { Combination []string Score ComboScore } func categorizeCombinations(combinations [][]string, categoryNames []string) map[string][]CategorizedCombination { categorized := map[string][]CategorizedCombination{ "quantum_ready": {}, "hybrid_classical": {}, "high_performance": {}, "maximum_security": {}, "balanced": {}, } for _, combo := range combinations { score := calculateCombinationScore(combo, categoryNames) catCombo := CategorizedCombination{Combination: combo, Score: score} if score.QuantumResistance >= 100 { categorized["quantum_ready"] = append(categorized["quantum_ready"], catCombo) } if score.QuantumResistance >= 40 { categorized["hybrid_classical"] = append(categorized["hybrid_classical"], catCombo) } if score.Performance >= 50 { categorized["high_performance"] = append(categorized["high_performance"], catCombo) } if score.ClassicalSecurity >= 75 { categorized["maximum_security"] = append(categorized["maximum_security"], catCombo) } if score.Total >= 40 && score.Total <= 80 { categorized["balanced"] = append(categorized["balanced"], catCombo) } } return categorized } func generateCombinationHash(combo []string) string { comboStr := strings.Join(combo, "|") hash := sha256.Sum256([]byte(comboStr)) return hex.EncodeToString(hash[:])[:12] } func generateCombinations(lists [][]string) [][]string { if len(lists) == 0 { return [][]string{{}} } firstList := lists[0] restOfLists := lists[1:] restCombinations := generateCombinations(restOfLists) var result [][]string for _, item := range firstList { for _, combo := range restCombinations { newCombo := append([]string{item}, combo...) result = append(result, newCombo) } } return result } func main() { fmt.Println("=== CryptoChainForge: Advanced Cryptographic Algorithm Suite Generator ===") fmt.Printf("Generated on: %s\n\n", time.Now().Format("2006-01-02 15:04:05")) // Generate all combinations var categoryNames []string for cat := range algorithmCategories { categoryNames = append(categoryNames, cat) } // Sort categoryNames for consistent iteration (optional, but good practice) // This assumes the order of categories matters for category_names[i] in calculateCombinationScore // If the order doesn't matter, this sort can be removed. // For now, I'll keep the order as in the Python script's iteration over keys. var algorithmLists = make([][]string, len(categoryNames)) for i, cat := range categoryNames { algorithmLists[i] = algorithmCategories[cat].Algorithms } fmt.Printf("Generating combinations from %d categories:\n", len(categoryNames)) for i, cat := range categoryNames { fmt.Printf(" %d. %s: %d algorithms\n", i+1, cat, len(algorithmLists[i])) } allCombinations := generateCombinations(algorithmLists) fmt.Printf("\nTotal unique algorithm combinations: %d\n", len(allCombinations)) // Categorize combinations fmt.Println("\nAnalyzing combinations...") categorizedCombos := categorizeCombinations(allCombinations, categoryNames) // Display summary statistics fmt.Printf("\n%s\n", strings.Repeat("=", 60)) fmt.Println("COMBINATION ANALYSIS SUMMARY") fmt.Printf("%s\n", strings.Repeat("=", 60)) for category, combos := range categorizedCombos { fmt.Printf("%s: %d combinations\n", strings.ReplaceAll(strings.Title(strings.ReplaceAll(category, "_", " ")), " ", ""), len(combos)) } // Display top recommendations for each category fmt.Printf("\n%s\n", strings.Repeat("=", 60)) fmt.Println("TOP RECOMMENDED COMBINATIONS") fmt.Printf("%s\n", strings.Repeat("=", 60)) for category, combos := range categorizedCombos { if len(combos) == 0 { continue } fmt.Printf("\n--- %s ---\n", strings.ToUpper(strings.ReplaceAll(category, "_", " "))) // Sort by total score and show top 3 // In Go, we'll use sort.Slice sort.Slice(combos, func(i, j int) bool { return combos[i].Score.Total > combos[j].Score.Total }) top3 := combos if len(combos) > 3 { top3 = combos[:3] } for idx, catCombo := range top3 { comboHash := generateCombinationHash(catCombo.Combination) fmt.Printf("\nRecommendation #%d [ID: %s]\n", idx+1, comboHash) fmt.Printf("Score: %d (QR: %d, CS: %d, Perf: %d)\n", catCombo.Score.Total, catCombo.Score.QuantumResistance, catCombo.Score.ClassicalSecurity, catCombo.Score.Performance) for j, categoryName := range categoryNames { fmt.Printf(" %s: %s\n", categoryName, catCombo.Combination[j]) } } } // Generate full detailed output (optional - can be saved to file) reader := bufio.NewReader(os.Stdin) fmt.Printf("\nGenerate full detailed output of all %d combinations? (y/N): ", len(allCombinations)) input, _ := reader.ReadString('\n') generateFullOutput := strings.TrimSpace(strings.ToLower(input)) == "y" if generateFullOutput { fmt.Printf("\n%s\n", strings.Repeat("=", 80)) fmt.Println("COMPLETE COMBINATION LISTING") fmt.Printf("%s\n", strings.Repeat("=", 80)) for i, combo := range allCombinations { score := calculateCombinationScore(combo, categoryNames) comboHash := generateCombinationHash(combo) fmt.Printf("\nCombination %d [ID: %s]\n", i+1, comboHash) fmt.Printf("Security Score: %d (Quantum: %d, Classical: %d, Performance: %d)\n", score.Total, score.QuantumResistance, score.ClassicalSecurity, score.Performance) for j, categoryName := range categoryNames { fmt.Printf(" %s: %s\n", categoryName, combo[j]) } if (i+1)%100 == 0 { fmt.Printf("\n--- Processed %d combinations ---\n", i+1) } } } // Export options fmt.Print("\nExport results? (j)son/(c)sv/(n)one: ") exportChoiceInput, _ := reader.ReadString('\n') exportChoice := strings.TrimSpace(strings.ToLower(exportChoiceInput)) if exportChoice == "j" { exportData := map[string]interface{}{ "metadata": map[string]interface{}{ "generated_at": time.Now().Format(time.RFC3339), "total_combinations": len(allCombinations), "categories": categoryNames, }, "categorized_results": map[string]interface{}{}, } categorizedResultsMap := exportData["categorized_results"].(map[string]interface{}) for category, combos := range categorizedCombos { var comboList []map[string]interface{} for _, catCombo := range combos { comboList = append(comboList, map[string]interface{}{ "combination": catCombo.Combination, "score": catCombo.Score, "hash": generateCombinationHash(catCombo.Combination), }) } categorizedResultsMap[category] = comboList } filename := fmt.Sprintf("crypto_combinations_%s.json", time.Now().Format("20060102_150405")) file, err := os.Create(filename) if err != nil { fmt.Printf("Error creating file: %v\n", err) return } defer file.Close() encoder := json.NewEncoder(file) encoder.SetIndent("", " ") err = encoder.Encode(exportData) if err != nil { fmt.Printf("Error encoding JSON: %v\n", err) return } fmt.Printf("Results exported to %s\n", filename) } else if exportChoice == "c" { filename := fmt.Sprintf("crypto_combinations_%s.csv", time.Now().Format("20060102_150405")) file, err := os.Create(filename) if err != nil { fmt.Printf("Error creating file: %v\n", err) return } defer file.Close() writer := csv.NewWriter(file) // CSV header headers := append([]string{"ID", "Category"}, categoryNames...) headers = append(headers, "Quantum_Score", "Classical_Score", "Performance_Score", "Total_Score") writer.Write(headers) for category, combos := range categorizedCombos { for _, catCombo := range combos { comboHash := generateCombinationHash(catCombo.Combination) row := []string{comboHash, category} row = append(row, catCombo.Combination...) row = append(row, fmt.Sprintf("%d", catCombo.Score.QuantumResistance)) row = append(row, fmt.Sprintf("%d", catCombo.Score.ClassicalSecurity)) row = append(row, fmt.Sprintf("%d", catCombo.Score.Performance)) row = append(row, fmt.Sprintf("%d", catCombo.Score.Total)) writer.Write(row) } } writer.Flush() if err := writer.Error(); err != nil { fmt.Printf("Error writing CSV: %v\n", err) return } fmt.Printf("Results exported to %s\n", filename) } fmt.Printf("\n%s\n", strings.Repeat("=", 60)) fmt.Println("CryptoChainForge: Analysis Complete") fmt.Printf("%s\n", strings.Repeat("=", 60)) }