-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCipher-Auto-Decoder2.html
More file actions
618 lines (529 loc) · 25.1 KB
/
Cipher-Auto-Decoder2.html
File metadata and controls
618 lines (529 loc) · 25.1 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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Caesar Cipher Auto-Decoder</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
padding: 20px;
}
.container {
max-width: 900px;
margin: 0 auto;
background: white;
border-radius: 15px;
box-shadow: 0 20px 60px rgba(0,0,0,0.3);
padding: 40px;
}
h1 {
color: #333;
margin-bottom: 10px;
text-align: center;
}
.subtitle {
text-align: center;
color: #668;
margin-bottom: 30px;
}
.upload-section {
background: #f8f9fa;
border: 2px dashed #667eea;
border-radius: 10px;
padding: 30px;
text-align: center;
margin-bottom: 30px;
transition: all 0.3s;
}
.upload-section:hover {
border-color: #764ba2;
background: #f0f1ff;
}
.file-input-wrapper {
position: relative;
display: inline-block;
}
input[type="file"] {
display: none;
}
.file-button {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 12px 30px;
border-radius: 25px;
cursor: pointer;
font-size: 16px;
font-weight: 600;
display: inline-block;
transition: transform 0.2s;
}
.file-button:hover {
transform: scale(1.05);
}
.file-status {
margin-top: 15px;
color: #28a745;
font-weight: 600;
}
.input-section {
margin-bottom: 30px;
}
label {
display: block;
margin-bottom: 10px;
color: #333;
font-weight: 600;
}
select {
width: 100%;
padding: 12px;
border: 2px solid #e0e0e0;
border-radius: 10px;
font-size: 16px;
background: white;
cursor: pointer;
transition: border-color 0.3s;
}
select:focus {
outline: none;
border-color: #667eea;
}
textarea {
width: 100%;
padding: 15px;
border: 2px solid #e0e0e0;
border-radius: 10px;
font-size: 16px;
font-family: 'Courier New', monospace;
resize: vertical;
transition: border-color 0.3s;
}
textarea:focus {
outline: none;
border-color: #667eea;
}
button {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border: none;
padding: 15px 40px;
font-size: 18px;
font-weight: 600;
border-radius: 25px;
cursor: pointer;
width: 100%;
transition: transform 0.2s;
}
button:hover {
transform: translateY(-2px);
}
button:disabled {
background: #ccc;
cursor: not-allowed;
transform: none;
}
.results {
margin-top: 30px;
}
.best-result {
background: linear-gradient(135deg, #d4fc79 0%, #96e6a1 100%);
border-radius: 10px;
padding: 25px;
margin-bottom: 25px;
box-shadow: 0 5px 15px rgba(0,0,0,0.1);
}
.best-result h2 {
color: #2d5016;
margin-bottom: 15px;
}
.result-text {
background: white;
padding: 20px;
border-radius: 8px;
font-family: 'Courier New', monospace;
font-size: 16px;
line-height: 1.6;
word-wrap: break-word;
}
.shift-info {
display: flex;
justify-content: space-between;
margin-bottom: 15px;
font-weight: 600;
}
.all-results {
background: #f8f9fa;
border-radius: 10px;
padding: 20px;
}
.all-results h3 {
color: #333;
margin-bottom: 20px;
}
.result-item {
background: white;
border-radius: 8px;
padding: 15px;
margin-bottom: 15px;
border-left: 4px solid #667eea;
}
.result-header {
display: flex;
justify-content: space-between;
margin-bottom: 10px;
font-weight: 600;
color: #667eea;
}
.result-preview {
font-family: 'Courier New', monospace;
color: #668;
font-size: 14px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.error {
background: #f8d7da;
color: #721c24;
padding: 15px;
border-radius: 8px;
margin-top: 20px;
border: 1px solid #f5c6cb;
}
</style>
</head>
<body>
<div class="container">
<h1>🔓 Cipher Auto-Decoder</h1>
<p class="subtitle">Upload your dictionary and automatically decrypt Caesar or ROT47 ciphers</p>
<div class="upload-section">
<div class="file-input-wrapper">
<label for="dictFile" class="file-button">Choose Dictionary File</label>
<input type="file" id="dictFile" accept=".txt,.dic,.text,text/plain">
</div>
<div class="file-status" id="fileStatus"></div>
<p style="color: #668; margin-top: 10px; font-size: 14px;">
Upload a text file with one word per line
</p>
</div>
<div class="input-section">
<label for="cipherType">Cipher Type:</label>
<select id="cipherType">
<option value="caesar">Caesar Cipher (26 shifts - letters only)</option>
<option value="rot47">ROT47 (94 shifts - all printable characters)</option>
<option value="combined">Combined (Caesar then ROT47, or ROT47 then Caesar)</option>
</select>
</div>
<div class="input-section">
<label for="encryptedText">Encrypted Message:</label>
<textarea id="encryptedText" rows="6" placeholder="Enter your encrypted message here..."></textarea>
</div>
<button id="decryptBtn" disabled>Decrypt Message</button>
<div id="results" class="results"></div>
</div>
<script>
let dictionary = new Set();
document.getElementById('dictFile').addEventListener('change', function(e) {
const file = e.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = function(event) {
const text = event.target.result;
const words = text.split(/\r?\n/).map(w => w.trim().toLowerCase()).filter(w => w.length > 0);
dictionary = new Set(words);
document.getElementById('fileStatus').textContent =
`✓ Dictionary loaded: ${dictionary.size} words`;
document.getElementById('decryptBtn').disabled = false;
};
reader.readAsText(file);
}
});
function caesarShift(text, shift) {
return text.split('').map(char => {
if (char.match(/[a-z]/i)) {
const code = char.charCodeAt(0);
const isUpper = char === char.toUpperCase();
const base = isUpper ? 65 : 97;
const shifted = ((code - base - shift + 26) % 26) + base;
return String.fromCharCode(shifted);
}
return char;
}).join('');
}
function rot47Shift(text, shift) {
return text.split('').map(char => {
const code = char.charCodeAt(0);
if (code >= 33 && code <= 126) {
const shifted = ((code - 33 - shift + 94) % 94) + 33;
return String.fromCharCode(shifted);
}
return char;
}).join('');
}
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
function scoreText(text) {
const words = text.toLowerCase().match(/\b[a-z]+\b/g) || [];
let dictionaryMatches = 0;
let totalScore = 0;
// Count dictionary matches (only for words 3+ letters)
let longWordCount = 0;
for (const word of words) {
if (word.length >= 3) {
longWordCount++;
if (dictionary.has(word)) {
dictionaryMatches++;
}
}
}
const hasDictMatches = longWordCount >= 2 && dictionaryMatches >= 2;
// Detect if this is primarily numeric content
const digitCount = (text.match(/\d/g) || []).length;
const alphaCount = (text.match(/[a-z]/gi) || []).length;
const hasLetters = alphaCount > 0;
const totalChars = text.replace(/\s/g, '').length; // Non-space characters
const digitRatio = digitCount / totalChars;
// ONLY use numeric mode if text is PURE numbers (no letters) and mostly digits
const isNumeric = digitCount >= 5 && !hasLetters && digitRatio >= 0.6 && !hasDictMatches;
if (isNumeric) {
// Numeric scoring mode - VERY STRICT
// Score 1: Valid number patterns - STRICTER
const numberPatterns = text.match(/\b\d+\.?\d*\b|\b\d+,\d{3}\b/g) || [];
const letterCount = (text.match(/[a-zA-Z]/g) || []).length;
// Penalize if there are letters mixed in (not real numeric content)
const letterPenalty = letterCount > 2 ? 0.3 : 1.0; // Severe penalty
const numberScore = numberPatterns.length > 0 ? 100 : 0;
totalScore += numberScore * 0.30 * letterPenalty; // 30% weight with penalty
// Score 2: Must look like pure numeric data
const numericRatio = digitCount / text.length;
const purityScore = numericRatio >= 0.5 ? 100 : (numericRatio * 200);
totalScore += purityScore * 0.25; // 25% weight
// Score 3: Penalty for mixed alphanumeric garbage
const mixedPattern = (text.match(/[a-z]\d|\d[a-z]/gi) || []).length;
const mixedPenalty = Math.max(0, 100 - (mixedPattern * 30)); // Heavy penalty
totalScore += mixedPenalty * 0.25; // 25% weight
// Score 4: Reasonable punctuation for numbers
const badPunctCount = (text.match(/[^0-9.,\-+$%\/\s]/g) || []).length;
const punctScore = Math.max(0, 100 - (badPunctCount * 15));
totalScore += punctScore * 0.20; // 20% weight
return {
matches: numberPatterns.length,
total: numberPatterns.length,
percentage: 100,
totalScore: totalScore.toFixed(1),
mode: 'numeric'
};
} else {
// Text scoring mode
// Dictionary score based on long words only
const dictScore = longWordCount > 0 ? (dictionaryMatches / longWordCount) * 100 : 0;
totalScore += dictScore * 0.60; // 60% weight - INCREASED FURTHER!
// Score 2: Common English bigrams (letter pairs)
const commonBigrams = ['th', 'he', 'in', 'er', 'an', 'ed', 're', 'on', 'at', 'en',
'nd', 'ti', 'es', 'or', 'te', 'of', 'st', 'ar', 'nt', 'to'];
let bigramCount = 0;
const lowerText = text.toLowerCase();
for (const bigram of commonBigrams) {
const count = (lowerText.match(new RegExp(bigram, 'g')) || []).length;
bigramCount += count;
}
const bigramScore = Math.min((bigramCount / (text.length / 10)) * 100, 100);
totalScore += bigramScore * 0.15; // 15% weight
// Score 3: Reasonable spacing (spaces should be ~15-20% of text)
const spaceCount = (text.match(/ /g) || []).length;
const spaceRatio = spaceCount / text.length;
const spaceScore = spaceRatio >= 0.10 && spaceRatio <= 0.25 ? 100 :
(spaceRatio >= 0.05 && spaceRatio <= 0.35 ? 50 : 0);
// Penalty for multiple consecutive spaces or weird spacing
const multiSpace = (text.match(/ +/g) || []).length;
const spacePenalty = Math.max(0, 100 - (multiSpace * 20));
totalScore += (spaceScore * 0.7 + spacePenalty * 0.3) * 0.05; // 5% weight
// Score 4: Penalty for non-standard characters mixed with text
// Count characters that shouldn't appear in normal text
const weirdChars = (text.match(/[^a-zA-Z0-9\s.,!?;:'"()\-]/g) || []).length;
const weirdPenalty = Math.max(0, 100 - (weirdChars * 25)); // 25 points per weird char
totalScore += weirdPenalty * 0.15; // 15% weight
// Score 5: Penalty for weird trailing punctuation (/, \, |, ~, etc.)
const trailingWeird = text.match(/[\/\\|~`@#$%^&*+=<>{}[\]]+$/);
const trailingPenalty = trailingWeird ? 50 : 100; // Even stronger penalty
totalScore += trailingPenalty * 0.05; // 5% weight
// Score 6: Proper sentence ending bonus (ends with . ! ?)
const properEnding = text.match(/[.!?]\s*$/);
const endingBonus = properEnding ? 100 : 90; // Reduced penalty for no ending
totalScore += endingBonus * 0.10; // 10% weight
return {
matches: dictionaryMatches,
total: longWordCount,
percentage: longWordCount > 0 ? (dictionaryMatches / longWordCount * 100).toFixed(1) : 0,
totalScore: totalScore.toFixed(1),
mode: 'text'
};
}
}
document.getElementById('decryptBtn').addEventListener('click', function() {
const encrypted = document.getElementById('encryptedText').value.trim();
const cipherType = document.getElementById('cipherType').value;
console.log('Decrypting:', encrypted, 'Type:', cipherType);
if (!encrypted) {
document.getElementById('results').innerHTML =
'<div class="error">Please enter an encrypted message.</div>';
return;
}
if (dictionary.size === 0) {
document.getElementById('results').innerHTML =
'<div class="error">Please upload a dictionary file first.</div>';
return;
}
const results = [];
console.log('Starting decryption...');
if (cipherType === 'combined') {
// Try ROT47 then Caesar (to decrypt messages encrypted Caesar then ROT47)
for (let rot47S = 0; rot47S < 94; rot47S++) {
for (let caesarS = 0; caesarS < 26; caesarS++) {
const step1 = rot47Shift(encrypted, rot47S);
const step2 = caesarShift(step1, caesarS);
const score = scoreText(step2);
// Original encryption shifts are the same as decryption shifts
// because our functions already shift backward
results.push({
shift: `ROT47(${rot47S}) → Caesar(${caesarS})`,
encryptionShift: `Caesar(${caesarS}) → ROT47(${rot47S})`,
text: step2,
score: score
});
}
}
// Try Caesar then ROT47 (to decrypt messages encrypted ROT47 then Caesar)
for (let caesarS = 0; caesarS < 26; caesarS++) {
for (let rot47S = 0; rot47S < 94; rot47S++) {
const step1 = caesarShift(encrypted, caesarS);
const step2 = rot47Shift(step1, rot47S);
const score = scoreText(step2);
// Original encryption shifts are the same as decryption shifts
results.push({
shift: `Caesar(${caesarS}) → ROT47(${rot47S})`,
encryptionShift: `ROT47(${rot47S}) → Caesar(${caesarS})`,
text: step2,
score: score
});
}
}
} else {
// Single cipher mode (original logic)
const maxShifts = cipherType === 'caesar' ? 26 : 94;
const shiftFunc = cipherType === 'caesar' ? caesarShift : rot47Shift;
for (let shift = 0; shift < maxShifts; shift++) {
const decrypted = shiftFunc(encrypted, shift);
const score = scoreText(decrypted);
results.push({
shift: shift,
text: decrypted,
score: score
});
}
}
results.sort((a, b) => b.score.totalScore - a.score.totalScore);
console.log('Total results:', results.length);
console.log('Top 5 scores:', results.slice(0, 5).map(r => ({score: r.score.totalScore, text: r.text.substring(0, 30)})));
// Get top candidates (within 0.5 points of best score)
const bestScore = parseFloat(results[0].score.totalScore);
const topCandidates = results.filter(r => parseFloat(r.score.totalScore) >= bestScore - 0.5);
console.log('Top candidates:', topCandidates.length);
// For combined mode, show results with good dictionary matches
let displayResults;
if (cipherType === 'combined') {
// Show top 20 by score, plus any with 50%+ dictionary match
const topByScore = results.slice(0, 20);
const goodDictMatches = results.filter(r =>
r.score.mode === 'text' &&
r.score.total >= 3 &&
parseFloat(r.score.percentage) >= 50
);
// Combine and deduplicate
const combined = [...topByScore, ...goodDictMatches];
const seen = new Set();
displayResults = combined.filter(r => {
const key = r.text;
if (seen.has(key)) return false;
seen.add(key);
return true;
});
} else {
displayResults = results;
}
const cipherName = cipherType === 'caesar' ? 'Caesar Cipher' :
cipherType === 'rot47' ? 'ROT47' : 'Combined Cipher';
let html = '<div class="all-results" style="margin-bottom: 30px;"><h3>🏆 Top Candidates (within 0.5 points)</h3>';
topCandidates.slice(0, 5).forEach((candidate, index) => {
const modeLabel = candidate.score.mode === 'numeric' ? 'Numeric Mode' : 'Text Mode';
const badge = index === 0 ? '🥇' : index === 1 ? '🥈' : index === 2 ? '🥉' : '⭐';
let shiftDisplay = '';
if (cipherType === 'combined') {
shiftDisplay = `
<div style="background: #fff3cd; padding: 12px; border-radius: 6px; margin-bottom: 15px; font-size: 14px;">
<div style="margin-bottom: 5px;"><strong>Encrypted with:</strong> ${candidate.encryptionShift} (estimated)</div>
<div><strong>Decrypted using:</strong> ${candidate.shift}</div>
</div>
`;
} else {
shiftDisplay = `
<div class="shift-info">
<span>Shift: ${candidate.shift}</span>
<span>Score: ${candidate.score.totalScore}/100 | ${candidate.score.mode === 'numeric' ? 'Numbers: ' + candidate.score.matches : 'Dict: ' + candidate.score.matches + '/' + candidate.score.total + ' (' + candidate.score.percentage + '%)'}</span>
</div>
`;
}
html += `
<div class="best-result" style="margin-bottom: 20px;">
<h2>${badge} Candidate ${index + 1} (${cipherName}) - ${modeLabel}</h2>
${shiftDisplay}
${cipherType === 'combined' ? '<div class="shift-info"><span></span><span>Score: ' + candidate.score.totalScore + '/100 | ' + (candidate.score.mode === 'numeric' ? 'Numbers: ' + candidate.score.matches : 'Dict: ' + candidate.score.matches + '/' + candidate.score.total + ' (' + candidate.score.percentage + '%)') + '</span></div>' : ''}
<div class="result-text">${escapeHtml(candidate.text)}</div>
</div>
`;
});
html += '</div>';
html += '</div>';
html += `
<div class="all-results">
<h3>All Top ${displayResults.length} Results (sorted by score)</h3>
`;
displayResults.forEach(r => {
const scoreDisplay = r.score.mode === 'numeric'
? `Score: ${r.score.totalScore}/100 | Numbers: ${r.score.matches}`
: `Score: ${r.score.totalScore}/100 | Dict: ${r.score.matches}/${r.score.total} (${r.score.percentage}%)`;
const shiftLabel = cipherType === 'combined'
? `<div style="font-size: 12px; color: #888; margin-top: 3px;">Encrypted: ${r.encryptionShift}</div><div style="font-size: 12px;">Decrypted: ${r.shift}</div>`
: `Shift ${r.shift}`;
html += `
<div class="result-item">
<div class="result-header">
<span>${shiftLabel}</span>
<span>${scoreDisplay}</span>
</div>
<div class="result-preview">${escapeHtml(r.text)}</div>
</div>
`;
});
if (cipherType === 'combined') {
html += `<p style="color: #668; margin-top: 15px; text-align: center;">
Showing ${displayResults.length} results (top scores + good dictionary matches from 4,888 combinations)
</p>`;
}
html += '</div>';
document.getElementById('results').innerHTML = html;
});
</script>
</body>
</html>