-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcipher.ts
More file actions
375 lines (326 loc) · 11.6 KB
/
cipher.ts
File metadata and controls
375 lines (326 loc) · 11.6 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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
/**
* Core cryptographic logic for the Multilayer Encryption system.
*/
import * as crypto from 'crypto';
import keysConfig from "./keys.json";
const SUBSTITUTION_MAP = keysConfig.SUBSTITUTION_MAP as Record<string, string>;
const SHUFFLED_ALPHABET = keysConfig.SHUFFLED_ALPHABET;
const map = keysConfig.map as Record<string, number>;
const RAIL_FENCE_NUM_RAILS = keysConfig.RAIL_FENCE_NUM_RAILS;
const RAIL_FENCE_ORDER = keysConfig.RAIL_FENCE_ORDER;
const PADDING_CHARS = keysConfig.PADDING_CHARS;
const PADDING_MAX_LENGTH = keysConfig.PADDING_MAX_LENGTH;
const PADDING_MARKER = keysConfig.PADDING_MARKER;
const KEY_MAPPING_START_UPPER = keysConfig.KEY_MAPPING_START_UPPER;
const KEY_MAPPING_START_LOWER = keysConfig.KEY_MAPPING_START_LOWER;
const KEY_MAPPING_FALLBACK = keysConfig.KEY_MAPPING_FALLBACK;
const SYSTEM_SALT = (keysConfig as any).SYSTEM_SALT;
const MATH_A_MULTIPLIER = (keysConfig as any).MATH_A_MULTIPLIER;
const MATH_B_MULTIPLIER = (keysConfig as any).MATH_B_MULTIPLIER;
function getConfig(key: string): any {
const val = (keysConfig as any)[key];
if (val === undefined) {
throw new Error(`CRITICAL CONFIGURATION ERROR: Missing required key '${key}' in keys.json. (No Fallbacks Allowed).`);
}
return val;
}
export const REVERSE_SUBSTITUTION_MAP: Record<string, string> = Object.fromEntries(
Object.entries(SUBSTITUTION_MAP).map(([k, v]) => [v, k])
);
/**
* Initializes the numeric mapping for the user key.
*/
export function getMappings(): Record<string, number> {
let startValue = KEY_MAPPING_START_UPPER;
for (let i = 0; i < 26; i++) {
map[String.fromCharCode(65 + i)] = startValue++; // A-Z
}
startValue = KEY_MAPPING_START_LOWER;
for (let i = 0; i < 26; i++) {
map[String.fromCharCode(97 + i)] = startValue++; // a-z
}
return map;
}
/**
* Caesar cipher with a shuffled alphabet.
*/
export function encryptCaesar(plaintext: string, shift: number): string {
let ciphertext = "";
for (let i = 0; i < plaintext.length; i++) {
const c = plaintext[i];
const code = c.charCodeAt(0);
if (code >= 32 && code <= 126) {
const originalIndex = SHUFFLED_ALPHABET.indexOf(c);
if (originalIndex !== -1) {
const newIndex = (originalIndex + shift) % SHUFFLED_ALPHABET.length;
ciphertext += SHUFFLED_ALPHABET[newIndex];
} else {
ciphertext += c;
}
} else {
ciphertext += c;
}
}
return ciphertext;
}
export function decryptCaesar(ciphertext: string, shift: number): string {
let plaintext = "";
for (let i = 0; i < ciphertext.length; i++) {
const c = ciphertext[i];
const code = c.charCodeAt(0);
if (code >= 32 && code <= 126) {
const originalIndex = SHUFFLED_ALPHABET.indexOf(c);
if (originalIndex !== -1) {
const newIndex = (originalIndex - shift % SHUFFLED_ALPHABET.length + SHUFFLED_ALPHABET.length) % SHUFFLED_ALPHABET.length;
plaintext += SHUFFLED_ALPHABET[newIndex];
} else {
plaintext += c;
}
} else {
plaintext += c;
}
}
return plaintext;
}
/**
* Rail Fence cipher implementation.
*/
export function railFenceEncrypt(text: string): string {
const numRails: number = RAIL_FENCE_NUM_RAILS;
const railOrder = RAIL_FENCE_ORDER;
if (numRails === 1) return text;
const rails: string[] = Array(numRails).fill("");
let row = 0;
let down = true;
for (let i = 0; i < text.length; i++) {
const c = text[i];
rails[row] += c;
if (row === 0) down = true;
else if (row === numRails - 1) down = false;
row += down ? 1 : -1;
}
return railOrder.map(i => rails[i]).join("");
}
export function railFenceDecrypt(text: string): string {
const numRails: number = RAIL_FENCE_NUM_RAILS;
const railOrder = RAIL_FENCE_ORDER;
if (numRails === 1) return text;
const pattern: number[] = [];
let row = 0;
let down = true;
for (let i = 0; i < text.length; i++) {
pattern.push(row);
if (row === 0) down = true;
else if (row === numRails - 1) down = false;
row += down ? 1 : -1;
}
const railLengths = Array(numRails).fill(0);
for (const pos of pattern) railLengths[pos]++;
const rails: string[] = Array(numRails).fill("");
let index = 0;
for (const i of railOrder) {
rails[i] = text.substring(index, index + railLengths[i]);
index += railLengths[i];
}
const railPos = Array(numRails).fill(0);
let result = "";
for (const pos of pattern) {
result += rails[pos][railPos[pos]++];
}
return result;
}
/**
* Substitution cipher logic.
*/
export function encryptSubstitution(text: string): string {
return text.split('').map(c => SUBSTITUTION_MAP[c] || c).join('');
}
export function decryptSubstitution(text: string): string {
return text.split('').map(c => REVERSE_SUBSTITUTION_MAP[c] || c).join('');
}
/**
* Process key and rounds.
*/
export function getKeyShifts(key: string): number[] {
const mappings = getMappings();
let encryptedNumbers = "";
for (const ch of key) {
if (mappings[ch] !== undefined) {
encryptedNumbers += mappings[ch] + " ";
} else if (/\d/.test(ch)) {
encryptedNumbers += ch + " ";
} else {
encryptedNumbers += KEY_MAPPING_FALLBACK;
}
}
const combined = encryptedNumbers.replace(/\D/g, '');
return combined.split('').map(Number);
}
export function getRepeatingShifts(keyShifts: number[], numRounds: number): number[] {
const keyPattern = keyShifts.join('');
let repeated = keyPattern;
while (repeated.length < numRounds) {
repeated += keyPattern;
}
return repeated.substring(0, numRounds).split('').map(Number);
}
/**
* Hidden padding logic.
*/
export function addHiddenPadding(plaintext: string): string {
const paddingChars = PADDING_CHARS;
const paddingUseCrypto = getConfig('PADDING_USE_CRYPTO_RANDOM');
const paddingLength = paddingUseCrypto ? crypto.randomInt(1, PADDING_MAX_LENGTH + 1) : Math.floor(Math.random() * PADDING_MAX_LENGTH) + 1;
let paddedText = "";
for (let i = 0; i < plaintext.length; i++) {
paddedText += plaintext[i];
for (let j = 0; j < paddingLength; j++) {
const r = paddingUseCrypto ? crypto.randomInt(0, paddingChars.length) : Math.floor(Math.random() * paddingChars.length);
paddedText += paddingChars[r];
}
if (i === 0) {
paddedText += PADDING_MARKER;
}
}
return paddedText;
}
export function removeHiddenPadding(paddedText: string): string {
const markerPos = paddedText.indexOf(PADDING_MARKER, 1);
if (markerPos === -1 || markerPos === 0) return paddedText;
const paddingLength = markerPos - 1;
let originalText = "";
for (let i = 0; i < paddedText.length; ) {
originalText += paddedText[i];
if (i === 0) {
i += paddingLength + 2;
} else {
i += paddingLength + 1;
}
}
return originalText;
}
/**
* Advanced Mathematical Layer (Affine Algebra)
*/
export function modInverse(a: number, m: number): number {
let m0 = m, y = 0, x = 1;
if (m === 1) return 0;
while (a > 1) {
let q = Math.floor(a / m);
let t = m;
m = a % m;
a = t;
t = y;
y = x - q * y;
x = t;
}
if (x < 0) x += m0;
return x;
}
export function encryptMath(text: string, shift: number): string {
const m = getConfig('MATH_MODULUS');
const a = (shift * MATH_A_MULTIPLIER * 2) + 1; // Guaranteed odd -> coprime with 65536
const b = shift * MATH_B_MULTIPLIER;
let result = "";
for (let i = 0; i < text.length; i++) {
let p = text.charCodeAt(i);
p = p ^ shift; // Non-linear bitwise modification
let c = (p * a + b) % m;
if (c < 0) c += m;
result += String.fromCharCode(c);
}
return result;
}
export function decryptMath(text: string, shift: number): string {
const m = getConfig('MATH_MODULUS');
const a = (shift * MATH_A_MULTIPLIER * 2) + 1;
const b = shift * MATH_B_MULTIPLIER;
const aInv = modInverse(a, m);
let result = "";
for (let i = 0; i < text.length; i++) {
const c = text.charCodeAt(i);
let val = (c - b) % m;
if (val < 0) val += m;
let p = (val * aInv) % m;
if (p < 0) p += m;
p = p ^ shift; // Reverse non-linear operation
result += String.fromCharCode(p);
}
return result;
}
/**
* Advanced Key Architecture (HMAC & PBKDF2)
*/
export function stretchKey(key: string, customSalt?: string): Buffer {
const mode = getConfig('KEY_STRETCH_MODE');
const masterKeyLength = getConfig('MASTER_KEY_LENGTH');
if (mode === 'pbkdf2') {
const salt = customSalt || getConfig('PBKDF2_SYSTEM_SALT');
return crypto.pbkdf2Sync(
key,
salt,
getConfig('PBKDF2_ITERATIONS'),
masterKeyLength,
getConfig('PBKDF2_DIGEST')
);
} else {
// Default to Scrypt
const salt = customSalt || SYSTEM_SALT;
return crypto.scryptSync(key, salt, masterKeyLength, {
N: getConfig('SCRYPT_N'),
r: getConfig('SCRYPT_R'),
p: getConfig('SCRYPT_P')
});
}
}
export function deriveKeys(masterKeyBuffer: Buffer, salt?: string): { aesKey: Buffer, hmacKey: Buffer } {
const alg = getConfig('HKDF_HASH_ALGORITHM');
const hkdfSalt = salt ? Buffer.from(salt, 'hex') : Buffer.alloc(0);
const aesKey = crypto.hkdfSync(alg, masterKeyBuffer, hkdfSalt, 'aes-256-gcm', 32);
const hmacKey = crypto.hkdfSync(alg, masterKeyBuffer, hkdfSalt, 'hmac-signature', 32);
return { aesKey: Buffer.from(aesKey), hmacKey: Buffer.from(hmacKey) };
}
export function generateHMAC(hmacKeyBuffer: Buffer, payload: string): string {
return crypto.createHmac(getConfig('HMAC_ALGORITHM'), hmacKeyBuffer).update(payload).digest('hex');
}
/**
* AES Cryptography Utilities
*/
export function generateRandomSalt(): string {
return crypto.randomBytes(32).toString('hex');
}
export function generateRandomIV(): string {
return crypto.randomBytes(12).toString('hex');
}
export function aesEncrypt(text: string, keyBuffer: Buffer, ivHex: string): { ciphertext: string, tag: string } {
const iv = Buffer.from(ivHex, 'hex');
const cipher = crypto.createCipheriv((keysConfig as any).AES_MODE, keyBuffer, iv);
let encrypted = cipher.update(text, 'utf16le', 'base64');
encrypted += cipher.final('base64');
return {
ciphertext: encrypted,
tag: cipher.getAuthTag().toString('hex')
};
}
export function aesDecrypt(ciphertextBase64: string, keyBuffer: Buffer, ivHex: string, tagHex: string): string {
const iv = Buffer.from(ivHex, 'hex');
const tag = Buffer.from(tagHex, 'hex');
const decipher = crypto.createDecipheriv((keysConfig as any).AES_MODE, keyBuffer, iv);
decipher.setAuthTag(tag);
let decrypted = decipher.update(ciphertextBase64, 'base64', 'utf16le');
decrypted += decipher.final('utf16le');
return decrypted;
}
/**
* Resolves the pipeline order for a specific round.
*/
export function getPipelineOrder(modifier: number): string[] {
const sequence = [...(keysConfig as any).PIPELINE_SEQUENCE];
if ((keysConfig as any).PIPELINE_MODE === "key-driven") {
for (let i = sequence.length - 1; i > 0; i--) {
const j = (modifier + i) % (i + 1);
[sequence[i], sequence[j]] = [sequence[j], sequence[i]];
}
}
return sequence;
}