-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcryptanalysis.html
More file actions
925 lines (845 loc) · 53.3 KB
/
cryptanalysis.html
File metadata and controls
925 lines (845 loc) · 53.3 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
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cryptanalysis Techniques — The Cipher Museum</title>
<meta name="description" content="Learn how codebreakers crack ciphers. Frequency analysis, Kasiski examination, index of coincidence, and modern computational methods.">
<meta property="og:title" content="Cryptanalysis Techniques — The Cipher Museum">
<meta property="og:description" content="Learn how codebreakers crack ciphers. Frequency analysis, Kasiski examination, index of coincidence, and modern computational methods.">
<meta property="og:type" content="website">
<meta property="og:url" content="https://ciphermuseum.com/cryptanalysis.html">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Cryptanalysis Techniques — The Cipher Museum">
<meta name="twitter:description" content="Learn how codebreakers crack ciphers. Frequency analysis, Kasiski examination, index of coincidence, and modern computational methods.">
<meta name="theme-color" content="#0a0a0f">
<link rel="canonical" href="https://ciphermuseum.com/cryptanalysis.html">
<link rel="icon" type="image/svg+xml" href="favicon.svg">
<link rel="stylesheet" href="css/museum.css">
<style>
.lab-grid { display:grid; grid-template-columns:repeat(auto-fill,minmax(300px,1fr)); gap:1.25rem; margin-bottom:2rem; }
.technique-card {
background:var(--s2); border:1px solid var(--s4); border-radius:var(--rl); padding:1.5rem;
transition:all var(--trs); cursor:default;
display:flex; flex-direction:column;
}
.technique-card .figure { margin-top:auto; }
.technique-card .technique-breaks { margin-top:.75rem; }
.technique-card:hover { border-color:var(--red-b); background:var(--s3); }
.technique-num { font-family:var(--fm); font-size:.6rem; letter-spacing:.15em; color:var(--tx3); margin-bottom:.5rem; }
.technique-name { font-family:var(--fd); font-size:1.15rem; color:var(--tx); margin-bottom:.35rem; letter-spacing:.04em; }
.technique-by { font-family:var(--fm); font-size:.65rem; letter-spacing:.1em; color:var(--gold-dim); margin-bottom:.75rem; }
.technique-desc { font-size:.95rem; color:var(--tx2); line-height:1.75; margin-bottom:.75rem; }
.technique-breaks { display:flex; flex-wrap:wrap; gap:.35rem; }
.timeline { display:flex; flex-direction:column; gap:0; }
.tl-item { display:grid; grid-template-columns:80px 1fr; gap:1.5rem; }
.tl-year { font-family:var(--fm); font-size:.72rem; color:var(--gold-dim); text-align:right; padding-top:1.2rem; }
.tl-body { padding:1rem 0 1.5rem 1.5rem; border-left:1px solid var(--s4); position:relative; }
.tl-body::before { content:''; position:absolute; left:-4px; top:1.3rem; width:7px; height:7px; border-radius:50%; background:var(--gold-dim); }
.tl-title { font-family:var(--fd); font-size:1.05rem; color:var(--tx); margin-bottom:.25rem; }
.tl-person { font-family:var(--fm); font-size:.62rem; letter-spacing:.1em; color:var(--gold); margin-bottom:.4rem; }
.tl-technique { font-family:var(--fm); font-size:.62rem; letter-spacing:.08em; color:var(--tx3); margin-bottom:.5rem; }
.tl-impact { font-size:.92rem; color:var(--tx2); line-height:1.7; }
.tl-item.legendary .tl-body::before { background:var(--gold); width:9px; height:9px; left:-5px; }
.tl-item.legendary .tl-body { border-color:var(--gold-b); }
/* Interactive challenge tabs */
.lab-tabs { display:flex; gap:0; background:var(--s3); border-radius:var(--r); padding:3px; margin-bottom:2rem; flex-wrap:wrap; }
.lab-tab { flex:1; min-width:140px; padding:.55rem 1rem; border:none; background:none; font-family:var(--fd); font-size:.75rem; letter-spacing:.1em; text-transform:uppercase; color:var(--tx3); cursor:pointer; border-radius:3px; transition:all var(--tr); }
.lab-tab.active { background:var(--gold); color:var(--black); font-weight:700; }
.lab-panel { display:none; } .lab-panel.active { display:block; }
.ic-display { font-family:var(--fm); font-size:2rem; color:var(--gold); text-align:center; padding:1rem; }
.ic-label { font-family:var(--fm); font-size:.62rem; letter-spacing:.15em; text-transform:uppercase; color:var(--tx3); text-align:center; }
.ic-bar-wrap { height:8px; background:var(--s4); border-radius:4px; margin:1rem 0; overflow:hidden; }
.ic-bar { height:100%; border-radius:4px; background:linear-gradient(90deg,var(--red),var(--gold),var(--green)); transition:width .4s ease; }
.kasiski-hits { margin-top:1rem; display:flex; flex-direction:column; gap:.4rem; max-height:200px; overflow-y:auto; }
.kasiski-hit { font-family:var(--fm); font-size:.75rem; background:var(--s3); border:1px solid var(--gold-b); border-radius:var(--r); padding:.5rem .75rem; color:var(--gold-lt); }
/* Responsive timeline */
@media(max-width:768px){
#timeline{grid-template-columns:1fr !important}
#timeline .timeline:first-child{padding-right:0}
#timeline .timeline:last-child{padding-left:0}
.lab-grid.reveal{opacity:1 !important;transform:none !important}
.lab-grid{grid-template-columns:1fr !important}
}
@media(max-width:600px){
.lab-tab{min-width:90px;font-size:.62rem;padding:.45rem .5rem}
}
/* Tab icons */
.lab-tab::before{margin-right:.4rem;font-size:.7rem}
#tab-btn-freq::before{content:'📊'}
#tab-btn-kasiski::before{content:'🔍'}
#tab-btn-ioc::before{content:'📐'}
#tab-btn-crib::before{content:'🔑'}
#tab-btn-kpa::before{content:'📄'}
#tab-btn-hillclimb::before{content:'⛰️'}
#tab-btn-anneal::before{content:'🧬'}
/* Lab textarea for older inline-styled inputs */
.lab-textarea{width:100%;padding:.8rem;background:var(--s3);border:1px solid var(--s4);border-radius:var(--r-sm);color:var(--tx);font-family:var(--fm);font-size:.82rem;resize:vertical}
.lab-textarea:focus{border-color:var(--gold-dim);outline:none}
.lab-result{margin-top:1.25rem;padding:1rem;background:var(--s2);border:1px solid var(--s4);border-radius:var(--r-sm);font-family:var(--fm);font-size:.82rem;color:var(--tx2);line-height:1.8;min-height:3rem}
</style>
</head>
<body>
<a class="skip-link" href="#main-content">Skip to main content</a>
<nav class="museum-nav" aria-label="Primary">
<div class="nav-inner">
<a href="index.html" class="nav-logo">
<svg class="nav-logo-icon" viewBox="0 0 32 32" fill="none">
<circle cx="16" cy="16" r="14" stroke="currentColor" stroke-width="1.5"/>
<circle cx="16" cy="16" r="8" stroke="currentColor" stroke-width="1"/>
<circle cx="16" cy="16" r="2" fill="currentColor"/>
<line x1="16" y1="2" x2="16" y2="6" stroke="currentColor" stroke-width="1.5"/>
<line x1="16" y1="26" x2="16" y2="30" stroke="currentColor" stroke-width="1.5"/>
<line x1="2" y1="16" x2="6" y2="16" stroke="currentColor" stroke-width="1.5"/>
<line x1="26" y1="16" x2="30" y2="16" stroke="currentColor" stroke-width="1.5"/>
</svg>
<span class="nav-logo-text">The Cipher Museum</span>
</a>
<ul class="nav-links">
<li><a href="index.html">Entrance</a></li>
<li><a href="museum-map.html">Museum Map</a></li>
<li><a href="halls/ancient.html">Halls</a></li>
<li><a href="cryptanalysis.html" class="active">Cryptanalysis</a></li>
<li><a href="modern.html">Modern Crypto</a></li>
</ul>
</div>
</nav>
<main id="main-content" tabindex="-1">
<div class="page-hero">
<div class="breadcrumb"><a href="index.html">Entrance</a><span>›</span>Cryptanalysis Techniques</div>
<span class="page-eyebrow">Special Exhibit · The Science of Breaking Codes</span>
<h1 class="page-title">Cryptanalysis Techniques</h1>
<p class="page-tagline">"To know how to defend, you must first know how to attack."</p>
<p class="page-desc">
Seven techniques that break almost every classical cipher in this museum — from Al-Kindi's frequency tables (850 AD) to modern hill-climbing algorithms.
</p>
<a href="lab/workbench.html" style="display:inline-block;margin-top:1rem;font-family:var(--fd);font-size:.82rem;letter-spacing:.1em;text-transform:uppercase;color:var(--gold);text-decoration:none;padding:.6rem 1.4rem;border:1px solid var(--gold-b);border-radius:var(--r);position:relative;z-index:1;transition:all .25s ease">Open Codebreaker's Workbench →</a>
</div>
<!-- ═══ MAIN CONTENT ══════════════════════════════════ -->
<div class="section">
<!-- 7 Techniques -->
<div class="section-head">
<span class="section-eyebrow">The Toolkit</span>
<h2 class="section-title">7 Techniques That Break Classical Ciphers</h2>
</div>
<div class="lab-grid reveal">
<div class="technique-card">
<div class="technique-num">Technique 01</div>
<div class="technique-name">Frequency Analysis</div>
<div class="technique-by">Al-Kindi · Baghdad · ~850 AD</div>
<p class="technique-desc">Languages have predictable letter frequencies. In English, E=12.7%, T=9.1%, A=8.2%. Any cipher that maps one letter to one symbol preserves these frequencies. Count the symbols, compare to known frequencies, recover the key.</p>
<figure class="figure" style="margin-top:1rem;">
<img src="images/artifacts/cryptanalysis-letter-frequency-chart.png" alt="Chart showing English letter frequency distribution used in cryptanalysis" loading="lazy">
<figcaption class="figure-caption">English letter frequency distribution — the foundation of frequency analysis attacks. Illustration: Google Gemini AI</figcaption>
</figure>
<div class="technique-breaks">
<a href="ciphers/caesar.html" class="badge sec-broken" style="text-decoration:none;">Caesar</a>
<a href="ciphers/monoalphabetic.html" class="badge sec-broken" style="text-decoration:none;">Monoalphabetic</a>
<a href="ciphers/homophonic.html" class="badge sec-broken" style="text-decoration:none;">Homophonic</a>
</div>
</div>
<div class="technique-card">
<div class="technique-num">Technique 02</div>
<div class="technique-name">Kasiski Examination</div>
<div class="technique-by">Friedrich Kasiski · 1863</div>
<p class="technique-desc">In a Vigenère cipher, the same plaintext + same key position = same ciphertext. Identical repeated strings in the ciphertext reveal probable key length. Their spacing is likely a multiple of the key length.</p>
<figure class="figure" style="margin-top:1rem;">
<img src="images/artifacts/cryptanalysis-kasiski-examination-vigenere-attack.png" alt="Diagram illustrating the Kasiski examination technique for breaking Vigenère ciphers" loading="lazy">
<figcaption class="figure-caption">Kasiski examination — finding repeated ciphertext sequences to determine Vigenère key length. Illustration: Google Gemini AI</figcaption>
</figure>
<div class="technique-breaks">
<a href="ciphers/vigenere.html" class="badge sec-broken" style="text-decoration:none;">Vigenère</a>
<a href="ciphers/beaufort.html" class="badge sec-broken" style="text-decoration:none;">Beaufort</a>
<a href="ciphers/gronsfeld.html" class="badge sec-broken" style="text-decoration:none;">Gronsfeld</a>
</div>
</div>
<div class="technique-card">
<div class="technique-num">Technique 03</div>
<div class="technique-name">Index of Coincidence</div>
<div class="technique-by">William Friedman · 1920</div>
<p class="technique-desc">Measures statistical similarity to natural language. English text has an IC of ~0.066. Random text has ~0.038. A polyalphabetic cipher produces values between these — and the IC can reveal the key length without finding repeated strings.</p>
<figure class="figure" style="margin-top:1rem;">
<img src="images/artifacts/cryptanalysis-index-of-coincidence.png" alt="Diagram explaining the Index of Coincidence technique used to distinguish encrypted text from natural language" loading="lazy">
<figcaption class="figure-caption">Index of Coincidence — measuring statistical deviation from random to determine cipher type and key length. Illustration: Google Gemini AI</figcaption>
</figure>
<div class="technique-breaks">
<a href="ciphers/vigenere.html" class="badge sec-broken" style="text-decoration:none;">Vigenère</a>
<a href="ciphers/running-key.html" class="badge sec-broken" style="text-decoration:none;">Running Key</a>
<span class="badge sec-broken">Polyalphabetic</span>
</div>
</div>
<div class="technique-card">
<div class="technique-num">Technique 04</div>
<div class="technique-name">Crib-Based Cryptanalysis</div>
<div class="technique-by">Polish Mathematicians · WWII Bletchley</div>
<p class="technique-desc">Guess probable plaintext words called "cribs" — military messages often start with standard phrases. The Enigma was broken partly because operators always began with WETTER (weather), HEIL HITLER, or ANX (a header). Known structure is a fatal weakness.</p>
<figure class="figure" style="margin-top:1rem;">
<img src="images/artifacts/cryptanalysis-crib-method.png" alt="Diagram illustrating the crib-based cryptanalysis method used to break Enigma by exploiting known plaintext patterns" loading="lazy">
<figcaption class="figure-caption">Crib-based cryptanalysis — exploiting predictable message headers and standard phrases to break machine ciphers. Illustration: Google Gemini AI</figcaption>
</figure>
<div class="technique-breaks">
<a href="ciphers/enigma.html" class="badge sec-broken" style="text-decoration:none;">Enigma</a>
<a href="ciphers/lorenz.html" class="badge sec-broken" style="text-decoration:none;">Lorenz</a>
<a href="ciphers/vigenere.html" class="badge sec-broken" style="text-decoration:none;">Vigenère</a>
</div>
</div>
<div class="technique-card">
<div class="technique-num">Technique 05</div>
<div class="technique-name">Known Plaintext Attack</div>
<div class="technique-by">Universal · Classical through Modern</div>
<p class="technique-desc">When some plaintext is known, the key can often be derived directly. The Hill cipher's matrix key is recoverable with just two known plaintext-ciphertext pairs by solving a system of linear equations. Enigma used weather forecasts as cribs.</p>
<figure class="figure" style="margin-top:1rem;">
<img src="images/artifacts/cryptanalysis-known-plaintext-attack.png" alt="Diagram showing how a known plaintext attack derives cipher keys from matched plaintext-ciphertext pairs" loading="lazy">
<figcaption class="figure-caption">Known plaintext attack — using matched plaintext-ciphertext pairs to recover the encryption key. Illustration: Google Gemini AI</figcaption>
</figure>
<div class="technique-breaks">
<a href="ciphers/hill.html" class="badge sec-broken" style="text-decoration:none;">Hill Cipher</a>
<a href="ciphers/enigma.html" class="badge sec-broken" style="text-decoration:none;">Enigma</a>
<a href="ciphers/lorenz.html" class="badge sec-broken" style="text-decoration:none;">Lorenz</a>
</div>
</div>
<div class="technique-card">
<div class="technique-num">Technique 06</div>
<div class="technique-name">Hill Climbing Search</div>
<div class="technique-by">Modern · Computer Era</div>
<p class="technique-desc">Start with a random key. Decrypt. Score the result using English language statistics — common digrams like TH, HE, IN. Make random changes to the key. Keep improvements, discard downgrades. Repeat millions of times. Works against substitution, Playfair, transposition.</p>
<figure class="figure" style="margin-top:1rem;">
<img src="images/artifacts/cryptanalysis-hill-climbing.png" alt="Diagram showing the hill climbing search algorithm iteratively improving cipher key guesses to break substitution ciphers" loading="lazy">
<figcaption class="figure-caption">Hill climbing search — iteratively refining key guesses by scoring decrypted output against English language statistics. Illustration: Google Gemini AI</figcaption>
</figure>
<div class="technique-breaks">
<a href="ciphers/monoalphabetic.html" class="badge sec-broken" style="text-decoration:none;">Substitution</a>
<a href="ciphers/playfair.html" class="badge sec-broken" style="text-decoration:none;">Playfair</a>
<span class="badge sec-broken">Transposition</span>
</div>
</div>
<div class="technique-card">
<div class="technique-num">Technique 07</div>
<div class="technique-name">Simulated Annealing / Genetic Algorithms</div>
<div class="technique-by">Modern · AI-Assisted</div>
<p class="technique-desc">Advanced optimization heuristics that explore key space more broadly than pure hill climbing. Genetic algorithms evolve populations of candidate keys. Simulated annealing occasionally accepts worse solutions to escape local optima. Breaks double transposition, Playfair, Hill cipher in seconds.</p>
<figure class="figure" style="margin-top:1rem;">
<img src="images/artifacts/cryptanalysis-simulated-annealing.png" alt="Diagram illustrating simulated annealing and genetic algorithm optimization techniques used in modern cryptanalysis" loading="lazy">
<figcaption class="figure-caption">Simulated annealing — escaping local optima to find the global best key through controlled randomness. Illustration: Google Gemini AI</figcaption>
</figure>
<div class="technique-breaks">
<a href="ciphers/double-transposition.html" class="badge sec-broken" style="text-decoration:none;">Double Transposition</a>
<a href="ciphers/playfair.html" class="badge sec-broken" style="text-decoration:none;">Playfair</a>
<a href="ciphers/hill.html" class="badge sec-broken" style="text-decoration:none;">Hill Cipher</a>
</div>
</div>
</div>
<div class="callout callout-warn" style="margin-bottom:2rem;">
<span class="callout-icon">⚡</span>
<div class="callout-body">
<p><strong>Speed comparison:</strong> A Vigenère with a 5-letter key that took weeks in the 1800s is cracked in <strong>under one second</strong> today. Monoalphabetic substitution falls in <strong>milliseconds</strong>.</p>
</div>
</div>
<svg class="section-divider" viewBox="0 0 180 6"><line x1="0" y1="3" x2="180" y2="3"/></svg>
<!-- Interactive Lab -->
<div class="section-head">
<span class="section-eyebrow">Hands-On</span>
<h2 class="section-title">Try the Techniques</h2>
<p class="section-sub">Apply cryptanalysis tools to real ciphertext.</p>
</div>
<div class="lab-tabs" role="tablist" aria-label="Cryptanalysis techniques">
<button class="lab-tab active" id="tab-btn-freq" role="tab" aria-selected="true" aria-controls="tab-freq" tabindex="0" onclick="showTab('freq', this)">Frequency Analysis</button>
<button class="lab-tab" id="tab-btn-kasiski" role="tab" aria-selected="false" aria-controls="tab-kasiski" tabindex="-1" onclick="showTab('kasiski', this)">Kasiski Examination</button>
<button class="lab-tab" id="tab-btn-ioc" role="tab" aria-selected="false" aria-controls="tab-ioc" tabindex="-1" onclick="showTab('ioc', this)">Index of Coincidence</button>
<button class="lab-tab" id="tab-btn-crib" role="tab" aria-selected="false" aria-controls="tab-crib" tabindex="-1" onclick="showTab('crib', this)">Crib Dragging</button>
<button class="lab-tab" id="tab-btn-kpa" role="tab" aria-selected="false" aria-controls="tab-kpa" tabindex="-1" onclick="showTab('kpa', this)">Known Plaintext</button>
<button class="lab-tab" id="tab-btn-hillclimb" role="tab" aria-selected="false" aria-controls="tab-hillclimb" tabindex="-1" onclick="showTab('hillclimb', this)">Hill Climbing</button>
<button class="lab-tab" id="tab-btn-anneal" role="tab" aria-selected="false" aria-controls="tab-anneal" tabindex="-1" onclick="showTab('anneal', this)">Simulated Annealing</button>
</div>
<!-- Tab: Frequency Analysis (SVG bar chart with English reference) -->
<div class="lab-panel active" id="tab-freq" role="tabpanel" aria-labelledby="tab-btn-freq">
<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:2rem;">
<div>
<div class="input-group" style="margin-bottom:1rem;">
<label class="input-label" for="labFreqInput">Paste Ciphertext</label>
<textarea class="museum-input" id="labFreqInput" rows="5" placeholder="Paste any ciphertext here… Try: KHOOR ZRUOG (Caesar shift 3)" oninput="labFreqUpdate()"></textarea>
</div>
<div id="labFreqResult" aria-live="polite" style="font-family:var(--fm);font-size:.82rem;color:var(--tx2);line-height:1.8;"></div>
<p style="margin-top:1rem;font-family:var(--fm);font-size:.72rem;color:var(--tx3);line-height:1.6;">IC = Σ n<sub>i</sub>(n<sub>i</sub>−1) / N(N−1) · <span id="labFreqIC" style="color:var(--gold);">—</span></p>
</div>
<div>
<p class="input-label" style="margin-bottom:.5rem;">Letter Frequencies <span style="font-size:.7rem;color:var(--tx3);">(gold = input, outline = English)</span></p>
<svg id="labFreqSVG" viewBox="0 0 572 170" style="width:100%;height:auto;" role="img" aria-label="Letter frequency bar chart"></svg>
<div id="labFreqHint" aria-live="polite" style="font-family:var(--fm);font-size:.72rem;color:var(--gold);margin-top:.75rem;"></div>
</div>
</div>
</div>
<!-- Tab: Kasiski -->
<div class="lab-panel" id="tab-kasiski" role="tabpanel" aria-labelledby="tab-btn-kasiski" hidden>
<div style="max-width:700px;">
<div class="input-group" style="margin-bottom:1.25rem;">
<label class="input-label" for="kasiskiInput">Paste Vigenère Ciphertext (strip spaces)</label>
<textarea class="museum-input" id="kasiskiInput" rows="4" placeholder="LXFOPVEFRNHRLXFOPVEFRNHR… Repeated sequences reveal key length." oninput="runKasiski()"></textarea>
</div>
<div id="kasiskiResult" aria-live="polite" style="font-family:var(--fm);font-size:.82rem;color:var(--tx2);line-height:1.8;"></div>
<div class="kasiski-hits" id="kasiskiHits" aria-live="polite"></div>
</div>
</div>
<!-- Tab: Index of Coincidence -->
<div class="lab-panel" id="tab-ioc" role="tabpanel" aria-labelledby="tab-btn-ioc" hidden>
<div style="max-width:600px;">
<div class="input-group" style="margin-bottom:1.25rem;">
<span class="input-label">Paste Ciphertext</span>
<textarea class="museum-input" id="iocInput" rows="4" placeholder="Paste ciphertext to calculate IC…" oninput="calcIC()"></textarea>
</div>
<div class="ic-display" id="icValue">—</div>
<div class="ic-label">Index of Coincidence</div>
<div class="ic-bar-wrap" style="margin-top:1rem;">
<div class="ic-bar" id="icBar" style="width:0%"></div>
</div>
<div style="display:flex;justify-content:space-between;font-family:var(--fm);font-size:.6rem;color:var(--tx3);">
<span>0.038 (Random)</span>
<span>0.052 (Vigenère)</span>
<span>0.066 (English)</span>
</div>
<div id="icInterpret" aria-live="polite" style="margin-top:1.5rem;font-family:var(--fm);font-size:.8rem;color:var(--tx2);line-height:1.7;"></div>
</div>
</div>
<!-- Tab: Crib Dragging -->
<div class="lab-panel" id="tab-crib" role="tabpanel" aria-labelledby="tab-btn-crib" hidden>
<div style="max-width:700px;">
<p style="margin-bottom:1rem;color:var(--tx2);">Drag a probable plaintext word ("crib") across the ciphertext. Where the XOR or subtraction produces readable text, you've found the key position. This is how Bletchley Park broke Enigma — they guessed words like WETTER and HEILHITLER.</p>
<div class="input-group" style="margin-bottom:1rem;">
<label class="input-label" for="cribCipher">Ciphertext (letters only)</label>
<textarea class="museum-input" id="cribCipher" rows="3" placeholder="LXFOPVEFRNHRLXFOPVEFRNHR… Try a Vigenère ciphertext."></textarea>
</div>
<div class="input-group" style="margin-bottom:1rem;">
<label class="input-label" for="cribWord">Crib (guessed plaintext word)</label>
<input type="text" class="museum-input" id="cribWord" placeholder="e.g. ATTACK or WEATHER" autocomplete="off" spellcheck="false" style="font-family:var(--fm);letter-spacing:.1em;">
</div>
<button class="btn btn-primary" onclick="runCribDrag()" style="font-size:.7rem;">Drag Crib</button>
<div id="cribResult" class="lab-result" aria-live="polite"></div>
</div>
</div>
<!-- Tab: Known Plaintext Attack -->
<div class="lab-panel" id="tab-kpa" role="tabpanel" aria-labelledby="tab-btn-kpa" hidden>
<div style="max-width:700px;">
<p style="margin-bottom:1rem;color:var(--tx2);">If you know some plaintext and its corresponding ciphertext, you can derive the key directly. For a Vigenère cipher: Key[i] = (Cipher[i] − Plain[i]) mod 26. Enter a matched pair to recover the key.</p>
<div class="input-group" style="margin-bottom:1rem;">
<label class="input-label" for="kpaPlain">Known Plaintext</label>
<input type="text" class="museum-input" id="kpaPlain" placeholder="e.g. ATTACKATDAWN" autocomplete="off" spellcheck="false" style="font-family:var(--fm);letter-spacing:.1em;">
</div>
<div class="input-group" style="margin-bottom:1rem;">
<label class="input-label" for="kpaCipher">Corresponding Ciphertext</label>
<input type="text" class="museum-input" id="kpaCipher" placeholder="e.g. LXFOPVEFRNHR" autocomplete="off" spellcheck="false" style="font-family:var(--fm);letter-spacing:.1em;">
</div>
<button class="btn btn-primary" onclick="runKPA()" style="font-size:.7rem;">Derive Key</button>
<div id="kpaResult" class="lab-result" aria-live="polite"></div>
</div>
</div>
<!-- Tab: Hill Climbing -->
<div class="lab-panel" id="tab-hillclimb" role="tabpanel" aria-labelledby="tab-btn-hillclimb" hidden>
<div style="max-width:700px;">
<p style="margin-bottom:1rem;color:var(--tx2);">Watch a hill-climbing algorithm break a Caesar cipher by scoring each shift against English letter frequencies. The algorithm starts at shift 0, tests neighbors, and keeps the best score — climbing toward the correct key.</p>
<div class="input-group" style="margin-bottom:1rem;">
<label class="input-label" for="hillInput">Ciphertext</label>
<input type="text" class="museum-input" id="hillInput" value="KHOOR ZRUOG" autocomplete="off" spellcheck="false" style="font-family:var(--fm);letter-spacing:.1em;">
</div>
<button class="btn btn-primary" id="hillBtn" onclick="runHillClimb()" style="font-size:.7rem;">Run Hill Climb</button>
<div id="hillOutput" style="margin-top:1.25rem;font-family:var(--fm);font-size:.82rem;line-height:2.2;color:var(--tx2);"></div>
</div>
</div>
<!-- Tab: Simulated Annealing -->
<div class="lab-panel" id="tab-anneal" role="tabpanel" aria-labelledby="tab-btn-anneal" hidden>
<div style="max-width:700px;">
<p style="margin-bottom:1rem;color:var(--tx2);">Simulated annealing improves on hill climbing by occasionally accepting worse solutions to escape local optima. Watch the temperature cool as the algorithm converges on the answer. Higher temperature = more exploration; lower = more exploitation.</p>
<div class="input-group" style="margin-bottom:1rem;">
<label class="input-label" for="annealInput">Ciphertext (Caesar)</label>
<input type="text" class="museum-input" id="annealInput" value="WKLV LV D WHVW PHVVDJH" autocomplete="off" spellcheck="false" style="font-family:var(--fm);letter-spacing:.1em;">
</div>
<button class="btn btn-primary" id="annealBtn" onclick="runAnneal()" style="font-size:.7rem;">Run Annealing</button>
<div id="annealOutput" style="margin-top:1.25rem;font-family:var(--fm);font-size:.82rem;line-height:2;color:var(--tx2);"></div>
</div>
</div>
<!-- 12 Famous Codebreaks -->
<div class="reveal" style="margin-top:5rem;">
<div class="section-head">
<span class="section-eyebrow">Historical Record</span>
<h2 class="section-title">12 Famous Codebreaks in History</h2>
<p class="section-sub">The moments that changed wars, toppled spies, and birthed the computer.</p>
</div>
<div style="display:grid;grid-template-columns:1fr 1fr;gap:0;" id="timeline">
<div class="timeline" style="padding-right:2rem;">
<div class="tl-item legendary">
<div class="tl-year">850 AD</div>
<div class="tl-body">
<div class="tl-title">Al-Kindi Breaks Substitution</div>
<div class="tl-person">Al-Kindi · Baghdad</div>
<div class="tl-technique">Technique: Frequency Analysis</div>
<p class="tl-impact">First documented scientific cryptanalysis. Introduced statistical analysis to codebreaking. Every cipher for the next 400 years was vulnerable.</p>
</div>
</div>
<div class="tl-item">
<div class="tl-year">1850s</div>
<div class="tl-body">
<div class="tl-title">Babbage Breaks Vigenère</div>
<div class="tl-person">Charles Babbage</div>
<div class="tl-technique">Technique: Repeating Sequence Analysis</div>
<p class="tl-impact">Ended the myth of the "indecipherable cipher." Babbage kept his method secret; Kasiski published it in 1863 and received the credit.</p>
</div>
</div>
<div class="tl-item">
<div class="tl-year">1863</div>
<div class="tl-body">
<div class="tl-title">Kasiski Publishes the Method</div>
<div class="tl-person">Friedrich Kasiski</div>
<div class="tl-technique">Technique: Pattern Repetition Analysis</div>
<p class="tl-impact">First widely published method for breaking polyalphabetic ciphers. European diplomatic Vigenère systems collapsed.</p>
</div>
</div>
<div class="tl-item legendary">
<div class="tl-year">1932</div>
<div class="tl-body">
<div class="tl-title">Polish Mathematicians Break Enigma</div>
<div class="tl-person">Rejewski, Różycki, Zygalski · Warsaw</div>
<div class="tl-technique">Technique: Permutation Analysis · Known Plaintext</div>
<p class="tl-impact">Created the first Enigma-breaking machines. Passed their work to Britain and France just before WWII began — giving Bletchley Park a head start.</p>
</div>
</div>
<div class="tl-item">
<div class="tl-year">1940</div>
<div class="tl-body">
<div class="tl-title">Friedman Breaks Japanese Purple</div>
<div class="tl-person">William Friedman · Washington DC</div>
<div class="tl-technique">Technique: Statistical Analysis · Machine Reconstruction</div>
<p class="tl-impact">The US could read Japanese diplomatic traffic before Pearl Harbor. The diplomatic warning was there — the military intelligence chain failed to act on it.</p>
</div>
</div>
<div class="tl-item">
<div class="tl-year">1970s</div>
<div class="tl-body">
<div class="tl-title">DES Differential Weakness Found</div>
<div class="tl-person">Eli Biham · Adi Shamir</div>
<div class="tl-technique">Technique: Differential Cryptanalysis</div>
<p class="tl-impact">Showed theoretical weaknesses in DES block cipher design. Revolutionized how cryptographers design and evaluate cipher strength.</p>
</div>
</div>
</div>
<div class="timeline" style="padding-left:2rem;border-left:1px solid var(--s4);">
<div class="tl-item legendary">
<div class="tl-year">WWII</div>
<div class="tl-body">
<div class="tl-title">Bletchley Park Breaks Enigma</div>
<div class="tl-person">Alan Turing · Gordon Welchman</div>
<div class="tl-technique">Technique: Crib Attacks · Electromechanical Bombe</div>
<p class="tl-impact">Shortened WWII by an estimated 2–4 years. The Bombe machine tested thousands of possible Enigma settings per minute, exploiting known plaintext cribs.</p>
</div>
</div>
<div class="tl-item legendary">
<div class="tl-year">1943</div>
<div class="tl-body">
<div class="tl-title">Lorenz Cipher Broken with Colossus</div>
<div class="tl-person">Bill Tutte · Tommy Flowers</div>
<div class="tl-technique">Technique: Known Plaintext · Early Computer Search</div>
<p class="tl-impact">Led to the creation of Colossus — the world's first programmable electronic computer. The direct ancestor of modern computing was built to break a cipher.</p>
</div>
</div>
<div class="tl-item">
<div class="tl-year">1943–80</div>
<div class="tl-body">
<div class="tl-title">VENONA: Soviet OTP Cracked</div>
<div class="tl-person">US Army Signal Intelligence</div>
<div class="tl-technique">Technique: Key Reuse Exploitation</div>
<p class="tl-impact">Soviet operators reused one-time pad key material under wartime pressure. VENONA decoded thousands of messages and exposed Julius Rosenberg and other Soviet spies in the US.</p>
</div>
</div>
<div class="tl-item">
<div class="tl-year">1993</div>
<div class="tl-body">
<div class="tl-title">Linear Cryptanalysis vs DES</div>
<div class="tl-person">Mitsuru Matsui</div>
<div class="tl-technique">Technique: Linear Cryptanalysis</div>
<p class="tl-impact">Found linear approximations of DES S-box operations, reducing the work to break DES from 2⁵⁶ to 2⁴³. Accelerated the case for replacing DES with AES.</p>
</div>
</div>
<div class="tl-item">
<div class="tl-year">1996</div>
<div class="tl-body">
<div class="tl-title">RSA Timing Attack</div>
<div class="tl-person">Paul Kocher</div>
<div class="tl-technique">Technique: Side-Channel Timing Analysis</div>
<p class="tl-impact">Broke RSA implementations by measuring how long decryption took. The math was fine — the implementation leaked secrets through time. Side-channel security became a new discipline.</p>
</div>
</div>
<div class="tl-item">
<div class="tl-year">2017</div>
<div class="tl-body">
<div class="tl-title">SHA-1 Collision (SHAttered)</div>
<div class="tl-person">Google · CWI Institute</div>
<div class="tl-technique">Technique: Collision Attack</div>
<p class="tl-impact">Produced two different PDF files with the same SHA-1 hash. Forced the entire internet to migrate from SHA-1 to SHA-256 and SHA-3. Cryptographic hash functions are not forever.</p>
</div>
</div>
</div>
</div>
</div>
<!-- Big Pattern -->
<div style="margin-top:4rem;">
<div class="callout callout-mystery">
<span class="callout-icon">🔍</span>
<div class="callout-body">
<p><strong>The Big Pattern:</strong> Most famous codebreaks succeeded not from pure mathematics, but from <strong>human mistakes</strong> (reused OTP keys, predictable message headers), <strong>protocol flaws</strong> (Enigma operators sending the same message twice), and <strong>implementation errors</strong> (RSA timing leaks). The math is often the last thing that fails. This is as true today as in Caesar's time.</p>
</div>
</div>
</div>
</div><!-- /section -->
</main>
<footer class="museum-footer">
<div class="footer-grid">
<div class="footer-brand">
<span class="footer-logo-text">The Cipher Museum</span>
<p class="footer-brand-desc">Open-source cryptography education. MIT License. GitHub Pages.</p>
</div>
<div>
<div class="footer-col-title">Techniques</div>
<ul class="footer-links">
<li><a href="#" onclick="showTab('freq',document.getElementById('tab-btn-freq'));return false;">Frequency Analysis</a></li>
<li><a href="#" onclick="showTab('kasiski',document.getElementById('tab-btn-kasiski'));return false;">Kasiski Examination</a></li>
<li><a href="#" onclick="showTab('ioc',document.getElementById('tab-btn-ioc'));return false;">Index of Coincidence</a></li>
<li><a href="#" onclick="showTab('crib',document.getElementById('tab-btn-crib'));return false;">Crib Dragging</a></li>
<li><a href="#" onclick="showTab('kpa',document.getElementById('tab-btn-kpa'));return false;">Known-Plaintext Attack</a></li>
<li><a href="#" onclick="showTab('hillclimb',document.getElementById('tab-btn-hillclimb'));return false;">Hill Climbing</a></li>
<li><a href="#" onclick="showTab('anneal',document.getElementById('tab-btn-anneal'));return false;">Simulated Annealing</a></li>
</ul>
</div>
<div>
<div class="footer-col-title">Continue</div>
<ul class="footer-links">
<li><a href="modern.html">Modern Cryptography →</a></li>
<li><a href="museum-map.html">Museum Map</a></li>
<li><a href="halls/ancient.html">Hall I</a></li>
</ul>
</div>
</div>
<div class="footer-bottom">
<span class="footer-copy">© The Cipher Museum · MIT License</span>
</div>
</footer>
<script>
function showTab(id, button) {
const targetPanel = document.getElementById('tab-' + id);
const targetButton = button || document.getElementById('tab-btn-' + id);
document.querySelectorAll('.lab-panel').forEach(panel => {
const isActive = panel === targetPanel;
panel.classList.toggle('active', isActive);
panel.hidden = !isActive;
});
document.querySelectorAll('[id^="tab-btn-"]').forEach(tab => {
const isActive = tab === targetButton;
tab.classList.toggle('active', isActive);
tab.setAttribute('aria-selected', isActive ? 'true' : 'false');
tab.tabIndex = isActive ? 0 : -1;
});
if (targetButton) {
targetButton.focus();
}
}
document.querySelectorAll('.lab-tab').forEach((tab, index, tabs) => {
tab.addEventListener('keydown', event => {
const previous = (index - 1 + tabs.length) % tabs.length;
const next = (index + 1) % tabs.length;
if (event.key === 'ArrowLeft') {
event.preventDefault();
tabs[previous].click();
} else if (event.key === 'ArrowRight') {
event.preventDefault();
tabs[next].click();
} else if (event.key === 'Home') {
event.preventDefault();
tabs[0].click();
} else if (event.key === 'End') {
event.preventDefault();
tabs[tabs.length - 1].click();
}
});
});
// ── Frequency Analysis ──────────────────────────────
const ALPHA = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const ENG_FREQ = [8.2,1.5,2.8,4.3,12.7,2.2,2.0,6.1,7.0,0.15,0.77,4.0,2.4,6.7,7.5,1.9,0.095,6.0,6.3,9.1,2.8,0.98,2.4,0.15,2.0,0.074];
function buildLabFreqSVG() {
const svg = document.getElementById('labFreqSVG');
if (!svg) return;
const bw = 16, gap = 6, h = 140, base = 155, maxEng = 12.7;
let html = '';
for (let i = 0; i < 26; i++) {
const x = i * (bw + gap);
const eh = (ENG_FREQ[i] / maxEng) * h;
// English reference bar (outline)
html += '<rect x="' + x + '" y="' + (base - eh) + '" width="' + bw + '" height="' + eh + '" fill="none" stroke="rgba(201,168,76,0.3)" stroke-width="1" rx="1"/>';
// Input frequency bar (filled, initially zero height)
html += '<rect id="svgbar_' + ALPHA[i] + '" x="' + x + '" y="' + base + '" width="' + bw + '" height="0" fill="#C9A84C" rx="1" style="transition:y .3s,height .3s;"/>';
// Letter label
html += '<text x="' + (x + bw / 2) + '" y="' + (base + 12) + '" text-anchor="middle" fill="#706878" font-family="monospace" font-size="8">' + ALPHA[i] + '</text>';
}
svg.innerHTML = html;
}
buildLabFreqSVG();
function labFreqUpdate() {
const txt = document.getElementById('labFreqInput').value.toUpperCase().replace(/[^A-Z]/g,'');
const result = document.getElementById('labFreqResult');
const hint = document.getElementById('labFreqHint');
const icEl = document.getElementById('labFreqIC');
if (!txt.length) { hint.textContent=''; result.textContent=''; icEl.textContent='—'; resetSVGBars(); return; }
const counts={}, len=txt.length, maxEng=12.7, h=140, base=155;
for (const ch of txt) counts[ch]=(counts[ch]||0)+1;
let maxCh='E',maxPct=0;
for (let i=0;i<26;i++){
const ch=ALPHA[i], pct=((counts[ch]||0)/len)*100;
const barH=(pct/maxEng)*h;
const el=document.getElementById('svgbar_'+ch);
if(el){el.setAttribute('y',base-barH);el.setAttribute('height',barH);el.setAttribute('fill',pct>8?'#C9A84C':pct>4?'#9A7A40':'#7a6530');}
if(pct>maxPct){maxPct=pct;maxCh=ch;}
}
// Compute IC inline
let icSum=0;
for (const k in counts) icSum+=counts[k]*(counts[k]-1);
const ic=len>1?icSum/(len*(len-1)):0;
icEl.textContent=ic.toFixed(4);
const guessShift=(maxCh.charCodeAt(0)-69+26)%26;
hint.textContent=`Most frequent: ${maxCh} (${maxPct.toFixed(1)}%) → If this is E, shift = ${guessShift}`;
result.innerHTML=`<strong>Total letters:</strong> ${len}<br><strong>Most common:</strong> ${maxCh} = ${maxPct.toFixed(1)}%<br><strong>Likely Caesar shift:</strong> ${guessShift}`;
}
function resetSVGBars(){for(let i=0;i<26;i++){const el=document.getElementById('svgbar_'+ALPHA[i]);if(el){el.setAttribute('y',155);el.setAttribute('height',0);}}}
// ── Index of Coincidence ────────────────────────────
function calcIC() {
const txt = document.getElementById('iocInput').value.toUpperCase().replace(/[^A-Z]/g,'');
const display = document.getElementById('icValue');
const bar = document.getElementById('icBar');
const interp = document.getElementById('icInterpret');
if (txt.length < 2) { display.textContent='—'; bar.style.width='0%'; interp.textContent=''; return; }
const counts={};
for (const ch of txt) counts[ch]=(counts[ch]||0)+1;
const n=txt.length;
let sum=0;
for (const k in counts) sum+=counts[k]*(counts[k]-1);
const ic=(sum/(n*(n-1)));
display.textContent=ic.toFixed(4);
const pct=Math.min(100,Math.max(0,((ic-0.038)/(0.066-0.038))*100));
bar.style.width=pct+'%';
let msg='';
if(ic>=0.063) msg='<strong style="color:var(--green)">IC ≈ English (0.066)</strong> — Likely a monoalphabetic or Caesar cipher. Apply frequency analysis directly.';
else if(ic>=0.050) msg='<strong style="color:var(--orange)">IC between random and English</strong> — Likely a polyalphabetic cipher (Vigenère). Try Kasiski examination to find key length.';
else msg='<strong style="color:var(--red)">IC ≈ Random (0.038)</strong> — Highly polyalphabetic or well-mixed. Key length may be very long, or text may be too short.';
interp.innerHTML=msg;
}
// ── Kasiski Examination ─────────────────────────────
function runKasiski() {
const txt = document.getElementById('kasiskiInput').value.toUpperCase().replace(/[^A-Z]/g,'');
const result = document.getElementById('kasiskiResult');
const hits = document.getElementById('kasiskiHits');
if (txt.length < 20) { result.textContent='Enter at least 20 characters.'; hits.innerHTML=''; return; }
const repeats={};
for (let len=3;len<=6;len++) {
for (let i=0;i<txt.length-len;i++) {
const seq=txt.substr(i,len);
if (!repeats[seq]) repeats[seq]=[];
repeats[seq].push(i);
}
}
const found=[];
for (const seq in repeats) {
if (repeats[seq].length>1) {
const positions=repeats[seq];
const spacings=[];
for (let i=1;i<positions.length;i++) spacings.push(positions[i]-positions[i-1]);
found.push({seq,positions,spacings});
}
}
if (!found.length) { result.textContent='No repeated sequences found. Text may be too short, or cipher is not Vigenère with a short key.'; hits.innerHTML=''; return; }
// GCD analysis
const allSpacings=found.flatMap(f=>f.spacings);
const gcds={};
for (const s of allSpacings) {
for (let k=2;k<=Math.min(s,15);k++) {
if (s%k===0) gcds[k]=(gcds[k]||0)+1;
}
}
const sorted=Object.entries(gcds).sort((a,b)=>b[1]-a[1]);
const likelyKey=sorted[0]?sorted[0][0]:null;
result.innerHTML=`Found <strong>${found.length}</strong> repeated sequences. Most likely key length: <strong style="color:var(--gold)">${likelyKey}</strong>`;
hits.innerHTML=found.slice(0,8).map(f=>
`<div class="kasiski-hit">"${f.seq}" at positions ${f.positions.join(', ')} — spacings: ${f.spacings.join(', ')}</div>`
).join('');
}
// ── Crib Dragging ───────────────────────────────────
function runCribDrag() {
const ct = document.getElementById('cribCipher').value.toUpperCase().replace(/[^A-Z]/g,'');
const crib = document.getElementById('cribWord').value.toUpperCase().replace(/[^A-Z]/g,'');
const out = document.getElementById('cribResult');
if (ct.length < 2 || crib.length < 1) { out.textContent='Enter ciphertext and a crib word.'; return; }
if (crib.length > ct.length) { out.textContent='Crib is longer than ciphertext.'; return; }
let html = '<div style="display:flex;flex-direction:column;gap:.4rem;max-height:300px;overflow-y:auto;">';
for (let pos = 0; pos <= ct.length - crib.length; pos++) {
let key = '';
for (let j = 0; j < crib.length; j++) {
key += ALPHA[(ct.charCodeAt(pos + j) - crib.charCodeAt(j) + 26) % 26];
}
const isRepeating = crib.length >= 3 && new Set(key.match(/.{1}/g)).size <= Math.ceil(key.length / 2);
const style = isRepeating ? 'border-color:var(--gold);background:var(--gold-glow);' : '';
html += '<div style="font-family:var(--fm);font-size:.75rem;background:var(--s3);border:1px solid var(--s4);border-radius:var(--r);padding:.5rem .75rem;color:var(--tx2);' + style + '">';
html += '<span style="color:var(--tx3);min-width:60px;display:inline-block;">Pos ' + pos + ':</span> ';
html += 'Key fragment = <span style="color:var(--gold-lt);font-weight:700;">' + key + '</span>';
if (isRepeating) html += ' <span style="color:var(--gold);margin-left:.5rem;">★ possible match</span>';
html += '</div>';
}
html += '</div>';
out.innerHTML = html;
}
// ── Known Plaintext Attack ──────────────────────────
function runKPA() {
const plain = document.getElementById('kpaPlain').value.toUpperCase().replace(/[^A-Z]/g,'');
const cipher = document.getElementById('kpaCipher').value.toUpperCase().replace(/[^A-Z]/g,'');
const out = document.getElementById('kpaResult');
if (!plain.length || !cipher.length) { out.textContent='Enter both plaintext and ciphertext.'; return; }
const len = Math.min(plain.length, cipher.length);
let key = '';
for (let i = 0; i < len; i++) {
key += ALPHA[(cipher.charCodeAt(i) - plain.charCodeAt(i) + 26) % 26];
}
// Detect repeating key
let repeatingKey = key;
for (let kl = 1; kl <= Math.floor(len / 2); kl++) {
const candidate = key.substring(0, kl);
let match = true;
for (let i = 0; i < len; i++) {
if (key[i] !== candidate[i % kl]) { match = false; break; }
}
if (match) { repeatingKey = candidate; break; }
}
let html = '<strong>Derived key stream:</strong> <span style="color:var(--gold-lt);font-family:var(--fm);letter-spacing:.1em;">' + key + '</span>';
if (repeatingKey.length < key.length) {
html += '<br><strong style="color:var(--green);">Repeating key detected:</strong> <span style="color:var(--gold);font-family:var(--fm);letter-spacing:.15em;font-size:1.1rem;font-weight:700;">' + repeatingKey + '</span>';
html += '<br><span style="color:var(--tx3);">Key length: ' + repeatingKey.length + '</span>';
}
// Verify: decrypt the cipher with this key
let decrypted = '';
for (let i = 0; i < cipher.length; i++) {
decrypted += ALPHA[(cipher.charCodeAt(i) - repeatingKey.charCodeAt(i % repeatingKey.length) + 26) % 26];
}
html += '<br><br><strong>Verification (decrypt full ciphertext):</strong><br><span style="font-family:var(--fm);letter-spacing:.1em;color:var(--tx);">' + decrypted + '</span>';
out.innerHTML = html;
}
// ── Hill Climbing ───────────────────────────────────
async function runHillClimb() {
const input = document.getElementById('hillInput').value.toUpperCase();
const out = document.getElementById('hillOutput');
const btn = document.getElementById('hillBtn');
btn.disabled = true;
out.innerHTML = '';
function score(text) {
const clean = text.replace(/[^A-Z]/g,'');
if (!clean.length) return 0;
let s = 0;
for (let i = 0; i < clean.length; i++) {
s += ENG_FREQ[clean.charCodeAt(i) - 65];
}
return s / clean.length;
}
function decrypt(text, shift) {
let r = '';
for (let i = 0; i < text.length; i++) {
const c = text.charCodeAt(i);
if (c >= 65 && c <= 90) r += String.fromCharCode(((c - 65 - shift + 26) % 26) + 65);
else r += text[i];
}
return r;
}
let current = 0;
let bestScore = score(decrypt(input, 0));
let steps = [{shift: 0, score: bestScore, text: decrypt(input, 0), action: 'Start'}];
for (let iter = 0; iter < 30; iter++) {
const neighbors = [(current + 1) % 26, (current + 25) % 26];
let improved = false;
for (const n of neighbors) {
const ns = score(decrypt(input, n));
steps.push({shift: n, score: ns, text: decrypt(input, n), action: ns > bestScore ? 'Climb ↑' : 'Reject ↓'});
if (ns > bestScore) {
bestScore = ns;
current = n;
improved = true;
break;
}
}
if (!improved) break;
}
for (let i = 0; i < steps.length; i++) {
const s = steps[i];
const line = document.createElement('div');
const color = s.action === 'Climb ↑' ? 'var(--green)' : s.action === 'Reject ↓' ? 'var(--red)' : 'var(--gold)';
line.style.cssText = 'padding:.3rem .6rem;border-radius:3px;';
line.innerHTML = '<span style="color:' + color + ';min-width:70px;display:inline-block;">' + s.action + '</span> Shift ' + s.shift.toString().padStart(2,'0') + ' (score ' + s.score.toFixed(1) + '): <span style="color:var(--tx);">' + s.text + '</span>';
if (i === steps.length - 1 && s.action !== 'Reject ↓') {
line.style.background = 'var(--gold-glow)';
line.innerHTML += ' <span style="color:var(--green);font-size:.7rem;margin-left:.5rem;">← Converged</span>';
}
out.appendChild(line);
await new Promise(r => setTimeout(r, 120));
}
btn.disabled = false;
}
// ── Simulated Annealing ─────────────────────────────
async function runAnneal() {
const input = document.getElementById('annealInput').value.toUpperCase();
const out = document.getElementById('annealOutput');
const btn = document.getElementById('annealBtn');
btn.disabled = true;
out.innerHTML = '';
function score(text) {
const clean = text.replace(/[^A-Z]/g,'');
if (!clean.length) return 0;
let s = 0;
for (let i = 0; i < clean.length; i++) s += ENG_FREQ[clean.charCodeAt(i) - 65];
return s / clean.length;
}
function decrypt(text, shift) {
let r = '';
for (let i = 0; i < text.length; i++) {
const c = text.charCodeAt(i);
if (c >= 65 && c <= 90) r += String.fromCharCode(((c - 65 - shift + 26) % 26) + 65);
else r += text[i];
}
return r;
}
let current = Math.floor(Math.random() * 26);
let bestShift = current, bestScore = score(decrypt(input, current));
let temp = 10.0;
const cooling = 0.85;
let steps = [];
for (let iter = 0; iter < 30 && temp > 0.1; iter++) {
const neighbor = (current + (Math.random() < 0.5 ? 1 : 25)) % 26;
const ns = score(decrypt(input, neighbor));
const delta = ns - bestScore;
const accept = delta > 0 || Math.random() < Math.exp(delta / temp);
const action = delta > 0 ? 'Better ↑' : (accept ? 'Accept ↔' : 'Reject ↓');
steps.push({shift: neighbor, score: ns, text: decrypt(input, neighbor), action, temp: temp.toFixed(2)});
if (accept) {
current = neighbor;
if (ns > bestScore) { bestScore = ns; bestShift = neighbor; }
}
temp *= cooling;
}
for (let i = 0; i < steps.length; i++) {
const s = steps[i];
const line = document.createElement('div');
const color = s.action === 'Better ↑' ? 'var(--green)' : s.action === 'Accept ↔' ? 'var(--orange)' : 'var(--red)';
line.style.cssText = 'padding:.3rem .6rem;border-radius:3px;';
line.innerHTML = '<span style="color:var(--tx3);min-width:55px;display:inline-block;">T=' + s.temp + '</span> <span style="color:' + color + ';min-width:65px;display:inline-block;">' + s.action + '</span> Shift ' + s.shift.toString().padStart(2,'0') + ': <span style="color:var(--tx);">' + s.text + '</span>';
out.appendChild(line);
await new Promise(r => setTimeout(r, 120));
}
const final = document.createElement('div');
final.style.cssText = 'margin-top:.75rem;padding:.6rem;background:var(--gold-glow);border-radius:3px;';
final.innerHTML = '<strong style="color:var(--gold);">Best result:</strong> Shift ' + bestShift + ' → <span style="color:var(--tx);font-family:var(--fm);letter-spacing:.1em;">' + decrypt(input, bestShift) + '</span> <span style="color:var(--green);font-size:.7rem;">(score ' + bestScore.toFixed(1) + ')</span>';
out.appendChild(final);
btn.disabled = false;
}
</script>
<script src="js/nav.js" defer></script>
<script src="js/lightbox.js"></script>
</body>
</html>