-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate_keys.ts
More file actions
192 lines (153 loc) · 8.01 KB
/
Copy pathgenerate_keys.ts
File metadata and controls
192 lines (153 loc) · 8.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
import * as fs from 'fs';
import * as path from 'path';
import * as crypto from 'crypto';
import { execSync } from 'child_process';
const keysPath = path.join(__dirname, 'keys.json');
// Fisher-Yates Shuffle using Cryptographically Secure Randomness
function secureShuffle(array: any[]): void {
for (let i = array.length - 1; i > 0; i--) {
const j = crypto.randomInt(0, i + 1);
[array[i], array[j]] = [array[j], array[i]];
}
}
function generateKeys() {
// console.log("Reading existing keys.json...");
let keysConfig: any = {};
if (fs.existsSync(keysPath)) {
const rawData = fs.readFileSync(keysPath, 'utf-8');
try {
keysConfig = JSON.parse(rawData);
} catch (e) {
console.warn("⚠️ Warning: keys.json is corrupted or empty. Bootstrapping a fresh configuration...");
keysConfig = {};
}
} else {
// console.log("ℹ️ keys.json not found. Initializing advanced cryptographic setup from scratch...");
keysConfig = {};
}
// 1. Generate the base printable ASCII characters (from space ' ' to '~')
const baseChars: string[] = [];
for (let i = 32; i <= 126; i++) {
baseChars.push(String.fromCharCode(i));
}
// 2. Generate a new secure SHUFFLED_ALPHABET
const shuffledForAlphabet = [...baseChars];
secureShuffle(shuffledForAlphabet);
keysConfig.SHUFFLED_ALPHABET = shuffledForAlphabet.join('');
// console.log("Generated new SHUFFLED_ALPHABET.");
// 3. Generate a new secure SUBSTITUTION_MAP
const shuffledForSubstitution = [...baseChars];
secureShuffle(shuffledForSubstitution);
const newSubstitutionMap: Record<string, string> = {};
for (let i = 0; i < baseChars.length; i++) {
newSubstitutionMap[baseChars[i]] = shuffledForSubstitution[i];
}
keysConfig.SUBSTITUTION_MAP = newSubstitutionMap;
// console.log("Generated new SUBSTITUTION_MAP.");
// 4. Generate a new secure RAIL_FENCE_ORDER based on dynamically chosen numRails
const numRails = crypto.randomInt(3, 13);
keysConfig.RAIL_FENCE_NUM_RAILS = numRails;
const railOrder: number[] = [];
for (let i = 0; i < numRails; i++) {
railOrder.push(i);
}
secureShuffle(railOrder);
keysConfig.RAIL_FENCE_ORDER = railOrder;
// console.log(`Generated new RAIL_FENCE_ORDER for ${numRails} rails.`);
// 5. Randomize PADDING_MARKER and Highly Dynamic PADDING_CHARS
const markerPool = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
const chosenMarker = markerPool[crypto.randomInt(0, markerPool.length)];
keysConfig.PADDING_MARKER = chosenMarker;
// Create a highly dynamic pool for PADDING_CHARS
const allChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+-=[]{}|;:',.<>?".split('');
const filteredChars = allChars.filter(c => c !== chosenMarker);
secureShuffle(filteredChars);
// Pick a random subset length between 15 and 70 characters
const subsetLength = crypto.randomInt(15, 71);
keysConfig.PADDING_CHARS = filteredChars.slice(0, subsetLength).join('');
// Randomize PADDING_MAX_LENGTH to play a "huge difference" in payload size
keysConfig.PADDING_MAX_LENGTH = crypto.randomInt(10, 151);
// console.log(`Generated dynamic PADDING - Marker: '${keysConfig.PADDING_MARKER}', Subset Length: ${subsetLength}, Max Length: ${keysConfig.PADDING_MAX_LENGTH}`);
// 6. Randomize Key Mapping Start Values and Fallback
keysConfig.KEY_MAPPING_START_UPPER = crypto.randomInt(20, 900);
keysConfig.KEY_MAPPING_START_LOWER = crypto.randomInt(10, 800);
keysConfig.KEY_MAPPING_FALLBACK = crypto.randomInt(10, 99).toString() + " ";
// console.log(`Generated new Key Mappings - UPPER: ${keysConfig.KEY_MAPPING_START_UPPER}, LOWER: ${keysConfig.KEY_MAPPING_START_LOWER}, FALLBACK: '${keysConfig.KEY_MAPPING_FALLBACK}'`);
// 7. Generate a new randomized map for special characters
const specialSymbols = "!@#$%^&*()_+-=[]{}|;:',.<>?".split('');
const newMap: Record<string, number> = {};
for (const sym of specialSymbols) {
newMap[sym] = crypto.randomInt(10, 1000);
}
keysConfig.map = newMap;
// console.log("Generated robust new character map for special symbols.");
// 8. Generate a dynamic KDF System Salt
keysConfig.SYSTEM_SALT = crypto.randomBytes(32).toString('hex');
keysConfig.PBKDF2_SYSTEM_SALT = crypto.randomBytes(32).toString('hex');
// console.log("Generated new SYSTEM_SALT and PBKDF2_SYSTEM_SALT (256-bit).");
// 9. Generate dynamic Affine Math Multipliers (Larger range for maximum entropy)
keysConfig.MATH_A_MULTIPLIER = crypto.randomInt(10, 1000);
keysConfig.MATH_B_MULTIPLIER = crypto.randomInt(10, 1000);
// console.log(`Generated hardened Affine Algebra Multipliers - A: ${keysConfig.MATH_A_MULTIPLIER}, B: ${keysConfig.MATH_B_MULTIPLIER}`);
// 10. Master Framework Config Definitions
keysConfig.MATH_MODULUS = 65536;
// Scrypt Memory-Hard Derivation
keysConfig.SCRYPT_N = 16384;
keysConfig.SCRYPT_R = 8;
keysConfig.SCRYPT_P = 1;
keysConfig.MASTER_KEY_LENGTH = 64; // Extracts 64 byte raw material
// HKDF Key Separation Logic
const hkdfHashes = ["sha256", "sha384", "sha512"];
keysConfig.HKDF_HASH_ALGORITHM = hkdfHashes[crypto.randomInt(0, hkdfHashes.length)];
// HMAC Data Integrity Validation
const hmacs = ["sha256", "sha384", "sha512"];
keysConfig.HMAC_ALGORITHM = hmacs[crypto.randomInt(0, hmacs.length)];
// PBKDF2 Digest Configuration
const pbkdf2Digests = ["sha256", "sha384", "sha512"];
keysConfig.PBKDF2_DIGEST = pbkdf2Digests[crypto.randomInt(0, pbkdf2Digests.length)];
keysConfig.PADDING_USE_CRYPTO_RANDOM = true;
keysConfig.ENABLE_MATH_LAYER = true;
keysConfig.ENABLE_SUBSTITUTION_LAYER = true;
keysConfig.ENABLE_RAIL_FENCE_LAYER = true;
keysConfig.ENABLE_CAESAR_LAYER = true;
keysConfig.PIPELINE_MODE = "key-driven";
// Randomize primary stretching mechanism for unpredictable defense
const matchModes = ["pbkdf2", "scrypt"];
keysConfig.KEY_STRETCH_MODE = matchModes[crypto.randomInt(0, matchModes.length)];
// Dynamic Complexity Scaling
keysConfig.PBKDF2_ITERATIONS = crypto.randomInt(300000, 600001);
keysConfig.CHAR_ENCODING = "utf16le";
// Metadata & Integrity Tracking
keysConfig.METADATA = {
GENERATED_AT: new Date().toISOString(),
SCHEMA_VERSION: "2.1.0-HARDENED",
SECURITY_LEVEL: "ULTRA"
};
keysConfig.ENABLE_HMAC = true;
keysConfig.ENABLE_INTEGRITY_CHECK = true;
keysConfig.AES_ENABLED = true;
keysConfig.AES_MODE = "aes-256-gcm";
// 11. Generate default pipeline sequence
const internalPipeline = ["caesar", "substitution", "rail_fence", "math"];
secureShuffle(internalPipeline);
keysConfig.PIPELINE_SEQUENCE = internalPipeline;
// 11b. Generate dynamic Master Pipeline
const masterPipelineStages = ["aes", "chaos", "padding", "substitution"];
secureShuffle(masterPipelineStages);
// HMAC must always be the last stage to ensure it signs the final state (including IV/Tag)
keysConfig.MASTER_PIPELINE = [...masterPipelineStages, "hmac"];
// console.log(`Generated new PIPELINE_SEQUENCE: [${keysConfig.PIPELINE_SEQUENCE.join(', ')}]`);
// console.log(`Generated new MASTER_PIPELINE: [${keysConfig.MASTER_PIPELINE.join(', ')}]`);
// console.log("Injected advanced Cryptographic Architecture Framework properties into keys.json!");
// Write back to keys.json
fs.writeFileSync(keysPath, JSON.stringify(keysConfig, null, 4), 'utf-8');
console.log("\n✅ SUCCESS: keys.json has been securely updated with new cryptographic combinations!");
console.log("\n⏳ Running automatic integrity tests on new keys...");
try {
execSync('npx tsx test_encryption.ts', { stdio: 'inherit' });
} catch (error) {
console.error("\n❌ Automatic test failed! The generated keys or cryptographic math has a flaw.");
process.exit(1);
}
}
generateKeys();