-
Notifications
You must be signed in to change notification settings - Fork 1
/
geheimschreiber.go
856 lines (723 loc) · 22.4 KB
/
geheimschreiber.go
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
package geheimschreiber
import (
"bufio"
"errors"
"fmt"
"log"
"os"
"regexp"
)
var WHEEL_SIZES = []int{47, 53, 59, 61, 64, 65, 67, 69, 71, 73}
var LARGE_WHEEL_SIZES = []int{26996, 26996, 26996, 26996, 26996, 26996, 26996, 26996, 26996, 26996}
var REMOVE_WHITESPACE_REGEX = regexp.MustCompile(`[\n\r]`)
var interestingCharacters = map[string]struct{}{"T": {},
"3": {},
"4": {},
"5": {},
"E": {},
"K": {},
"Q": {},
"6": {},
"X": {},
"V": {}}
//FindUniqueBitIndex takes an integer which must be a permutation of "00001" or "11110"
//and returns the index (counting from the left) of the unique bit
func FindUniqueBitIndex(i int) (index int, err error) {
switch i {
case 1:
index = 4
return
case 2:
index = 3
return
case 4:
index = 2
return
case 8:
index = 1
return
case 16:
index = 0
return
case 30:
index = 4
return
case 29:
index = 3
return
case 27:
index = 2
return
case 23:
index = 1
return
case 15:
index = 0
return
}
return -1, fmt.Errorf("error: FindUniqueBitIndex called with an invalid integer input")
}
//We need these only because we cannot take the address of an integer literal
var ZERO = 0
var ONE = 1
var TRANSPOSITION_PATTERN = [][][]*int{
[][]*int{
[]*int{&ZERO, &ZERO, nil, nil, nil},
[]*int{&ZERO, &ONE, &ZERO, nil, nil},
[]*int{&ZERO, &ONE, &ONE, &ZERO, nil},
[]*int{nil, nil, nil, nil, nil},
[]*int{nil, nil, nil, nil, nil},
},
[][]*int{
[]*int{nil, &ONE, nil, nil, nil},
[]*int{nil, &ZERO, &ZERO, nil, nil},
[]*int{nil, &ZERO, &ONE, &ZERO, nil},
[]*int{nil, &ZERO, &ONE, &ONE, &ZERO},
[]*int{nil, &ZERO, &ONE, &ONE, &ONE},
},
[][]*int{
[]*int{nil, nil, nil, nil, nil},
[]*int{nil, nil, &ONE, nil, nil},
[]*int{nil, nil, &ZERO, &ZERO, nil},
[]*int{nil, nil, &ZERO, &ONE, &ZERO},
[]*int{nil, nil, &ZERO, &ONE, &ONE},
},
[][]*int{
[]*int{nil, nil, nil, nil, nil},
[]*int{nil, nil, nil, nil, nil},
[]*int{nil, nil, nil, &ONE, nil},
[]*int{nil, nil, nil, &ZERO, &ZERO},
[]*int{nil, nil, nil, &ZERO, &ONE},
},
[][]*int{
[]*int{&ONE, &ZERO, nil, nil, nil},
[]*int{&ONE, &ONE, &ZERO, nil, nil},
[]*int{&ONE, &ONE, &ONE, &ZERO, nil},
[]*int{nil, nil, nil, nil, nil},
[]*int{nil, nil, nil, nil, nil},
},
}
//inferTransposeBits takes a source integer and a destination integer corresponding to
//(plaintext XORed with wheels 0-4) and ciphertext, respectively
//It returns what we know about the transpose wheels (wheels 5-9)
func inferTransposeBits(source, dest int) []*int {
return TRANSPOSITION_PATTERN[source][dest]
}
// TRANSPOSE_PROBS[i][j] is prob ci ends up in j'th bit
var TRANSPOSE_PROBS = [][]float64{
[]float64{0.25, 0.125, 0.0625, 0.25 + 0.03125, 0.25 + 0.03125},
[]float64{0.5, 0.25, 0.125, 0.0625, 0.0625},
[]float64{0, 0.5, 0.25, 0.125, 0.125},
[]float64{0, 0, 0.5, 0.25, 0.25},
[]float64{0.25, 0.125, 0.0625, 0.03125 + 0.25, 0.03125 + 0.025}}
var alphabet = map[string]int{
"2": 0,
"T": 1,
"3": 2,
"O": 3,
"4": 4,
"H": 5,
"N": 6,
"M": 7,
"5": 8,
"L": 9,
"R": 10,
"G": 11,
"I": 12,
"P": 13,
"C": 14,
"V": 15,
"E": 16,
"Z": 17,
"D": 18,
"B": 19,
"S": 20,
"Y": 21,
"F": 22,
"X": 23,
"A": 24,
"W": 25,
"J": 26,
"6": 27,
"U": 28,
"Q": 29,
"K": 30,
"7": 31,
}
//Brute force
//TODO do better
func invertAlphabet(i int) (string, error) {
for key, val := range alphabet {
if val == i {
return key, nil
}
}
return "", errors.New("matching key not found in alphabet")
}
type Wheel struct {
Items []int
CurrentIndex int //Starts at zero
MaxSize int
}
func NewWheel(items []int) (w *Wheel) {
w = new(Wheel)
w.MaxSize = len(items)
w.Items = items
w.CurrentIndex = 0
return w
}
//CurrentBit gets the current bit on the given wheel AND ticks the wheel forward to the next value
func (w *Wheel) CurrentBit() (bit int) {
bit = w.Items[w.CurrentIndex]
w.CurrentIndex = (w.CurrentIndex + 1) % w.MaxSize
return
}
//Tick increments the current wheel (but ignore the actual value read from the wheel)
func (w *Wheel) Tick() {
w.CurrentBit()
}
//TickAll takes a slice of wheels and calls Tick() on all of them
func TickAll(ws []*Wheel) {
for _, w := range ws {
w.Tick()
}
}
func (w Wheel) Equals(other Wheel) bool {
if w.MaxSize != other.MaxSize {
return false
}
for i, item := range w.Items {
if item != other.Items[i] {
return false
}
}
return true
}
//xorCurrentCharacter takes an integer representation of a character
//and XORs it with the current bit on each of wheel b0 through b4
//This assumes that "wheels" is a valid array of wheels of length <= 5
func xorCurrentCharacter(wheels []*Wheel, input int) int {
//Iterate over each of the wheels (from the left)
for i := 0; i < 5; i++ {
currentBit := wheels[i].CurrentBit()
input = input ^ currentBit<<(4-uint(i))
}
return input
}
func EncryptString(wheels []*Wheel, plaintext string) (string, error) {
result := ""
for _, character := range plaintext {
char := string(character)
if char == "\n" || char == "\r" {
result += char
continue
}
encrypted, err := encryptCharacter(wheels, char)
if err != nil {
return "", err
}
result += encrypted
}
return result, nil
}
//EncryptCharacter takes a single character and encrypts it with all ten wheels in Wheels
func encryptCharacter(wheels []*Wheel, char string) (string, error) {
c, ok := alphabet[char]
if !ok {
log.Printf("Cannot find character %s adf", char)
return "", errors.New("error: character not in alphabet")
}
var i uint8
for i = 0; i < 5; i++ {
current_bit := wheels[i].CurrentBit()
c = (c ^ (current_bit << (4 - i))) //
}
if wheels[5].CurrentBit() == 1 {
c = interchangeBits(c, 0, 4)
}
if wheels[6].CurrentBit() == 1 {
c = interchangeBits(c, 0, 1)
}
if wheels[7].CurrentBit() == 1 {
c = interchangeBits(c, 1, 2)
}
if wheels[8].CurrentBit() == 1 {
c = interchangeBits(c, 2, 3)
}
if wheels[9].CurrentBit() == 1 {
c = interchangeBits(c, 3, 4)
}
encrypted_character, err := invertAlphabet(c)
return encrypted_character, err
}
func DecryptString(wheels []*Wheel, ciphertext string) (string, error) {
result := ""
for _, character := range ciphertext {
char := string(character)
if char == "\n" || char == "\r" {
result += char
continue
}
decrypted, err := decryptCharacter(wheels, char)
if err != nil {
return "", err
}
result += decrypted
}
return result, nil
}
func decryptCharacter(wheels []*Wheel, char string) (string, error) {
c, ok := alphabet[char]
if !ok {
return "", errors.New("error: character not in alphabet")
}
if wheels[9].CurrentBit() == 1 {
c = interchangeBits(c, 3, 4)
}
if wheels[8].CurrentBit() == 1 {
c = interchangeBits(c, 2, 3)
}
if wheels[7].CurrentBit() == 1 {
c = interchangeBits(c, 1, 2)
}
if wheels[6].CurrentBit() == 1 {
c = interchangeBits(c, 0, 1)
}
if wheels[5].CurrentBit() == 1 {
c = interchangeBits(c, 0, 4)
}
//Order of XOR doesn't matter
var i uint8
for i = 0; i < 5; i++ {
current_bit := wheels[i].CurrentBit()
c = (c ^ (current_bit << (4 - i))) //
}
decrypted_character, err := invertAlphabet(c)
return decrypted_character, err
}
//getNthBit returns the nth bit from the right (ie, place value 2^n)
//For example, getNthBit(2, 0) should return 0
func getNthBit(i int, n int) int {
return (i & (1 << uint(n))) >> uint(n)
}
//interchangeBits takes a uint8 (c) with only FIVE significant bits
//and interchanges the ith and jth bit
//i must be less than j
func interchangeBits(c int, i uint8, j uint8) int {
//Get the ith digit of c
ci_tmp := c & (16 >> i)
//Get the jth digit of c
cj_tmp := c & (16 >> j)
c = c &^ (16 >> i)
c = c | (cj_tmp << (j - i))
//Set cj to be the OLD value of ci
c = c &^ (16 >> j)
c = c | (ci_tmp >> (j - i))
return c
}
func ResetWheels(wheels []*Wheel) {
for _, w := range wheels {
w.CurrentIndex = 0
}
}
//learnedWheelToWheel converts a learnedWheel array to a Wheel struct
//Assume that all *int values are non-nil; otherwise this will panic
func learnedWheelToWheel(learnedWheel []*int) *Wheel {
items := make([]int, len(learnedWheel))
for i, _ := range learnedWheel {
items[i] = *learnedWheel[i]
}
w := NewWheel(items)
return w
}
//TODO these don't really need to be separate functions, as long as the format is the same (which it currently is)
//Via http://stackoverflow.com/questions/8757389/reading-file-line-by-line-in-go
func Readln(r *bufio.Reader) (string, error) {
var (
isPrefix bool = true
err error = nil
line, ln []byte
)
for isPrefix && err == nil {
line, isPrefix, err = r.ReadLine()
ln = append(ln, line...)
}
return string(ln), err
}
func parseCiphertext(filename string) (string, string) {
f, err := os.Open(filename)
if err != nil {
fmt.Printf("error opening file: %v\n", err)
panic(err)
}
ciphertext := ""
plaintext := ""
scanner := bufio.NewScanner(f)
for scanner.Scan() {
currentLine := scanner.Text()
//Assume every line is at least 13 characters
plaintext += "UMUM4VEVE35"
ciphertext += currentLine[:11]
for _, _ = range currentLine[12 : len(currentLine)-1] {
ciphertext += "-"
plaintext += "-"
}
ciphertext += currentLine[len(currentLine)-2:]
plaintext += "35"
}
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "reading standard input:", err)
}
ciphertext = REMOVE_WHITESPACE_REGEX.ReplaceAllString(ciphertext, "")
return ciphertext, plaintext
}
//func learnFirstFiveWheels learns all spoke values from the first five wheels
//This happens to work for the plaintext/ciphertext pair that we used for testing; it is not guaranteed to work for all texts, particularly shorter texts
func learnFirstFiveWheels(learnedWheels [][]*int, plaintext string, ciphertext string) {
//TODO don't use a global variable (learnedWheels) to store the results
// Iterate across plaintext. For each character:
// For each bit c0-c4:
// Examine all possible destination bits for ci
// Add p to implied element of appropriate spoke's pair
// Examine all observed spoke 0-1 pairs. For all that pass a threshold, declare it 0 or 1.
// Abort if any spoke fails this threshold.
//Iterate over plaintext and ciphertext in lockstep
// For each cipherchar 2 or 7 encountered:
// Learn b0-b4 and save to appropriate slot on each wheel
// If all b0-b4 learned:
// Else:
for index, plainRune := range plaintext {
plainChar := string(plainRune)
if plainChar == "-" {
continue
}
plainInt := alphabet[plainChar]
cipherRune := rune(ciphertext[index])
cipherChar := string(cipherRune)
cipherInt := alphabet[cipherChar]
if cipherInt == 0 || cipherInt == 31 {
//All output bits were 0, so we know that EVERY plaintext bit XORed with b_{i} to 0, for all i
//To learn the bits b_{i}, we XOR again and store into the appropriate b_{i} slot
mask := cipherInt ^ plainInt
//Store each bit of mask in the appropriate b_{i} slot
for i := 0; i < 5; i++ {
bi := getNthBit(mask, 4-i)
if learnedWheels[i][index%LARGE_WHEEL_SIZES[i]] != nil && *learnedWheels[i][index%LARGE_WHEEL_SIZES[i]] != bi {
panic(fmt.Errorf("error: inconsistent XOR bit saved at %d for wheel %d", index, i))
}
learnedWheels[i][index%LARGE_WHEEL_SIZES[i]] = &bi
}
}
}
}
//learnEasyTransposeBits learns all of the bits in wheels 5-8, and most (but not all) of the bits in wheel 9
func learnEasyTransposeBits(wheels []*Wheel, learnedWheels [][]*int, plaintext, ciphertext string) {
//Iterate over the ciphertext. If the ciphercharacter is one of T,3,4,5,E,K,Q,6,X,V,
//we XOR the plainInt with the current state of the XOR wheels (which is known)
//This gives a permutation of "00001" or "11110"
//The current cipherInt must also be a (potentially different) permutation of the same two bit sequences
//Based on where the unique bit (the unique 0 or unique 1) started and ended, we can deduce at least 2 transposed bits
for index, plainRune := range plaintext {
plainChar := string(plainRune)
if plainChar == "-" {
TickAll(wheels)
continue
}
plainInt := alphabet[plainChar]
cipherRune := rune(ciphertext[index])
cipherChar := string(cipherRune)
cipherInt := alphabet[cipherChar]
//Check if the cipherCharacter is one of the characters we care about
if _, present := interestingCharacters[cipherChar]; present {
//XOR the plainInt with the current state of the XOR wheels
xoredValue := xorCurrentCharacter(wheels, plainInt)
sourceIndex, err := FindUniqueBitIndex(xoredValue)
if err != nil {
panic(err)
}
destIndex, err := FindUniqueBitIndex(cipherInt)
if err != nil {
panic(err)
}
inferredBits := inferTransposeBits(sourceIndex, destIndex)
for i, bitP := range inferredBits {
if bitP != nil {
bit := *bitP
//Check that we are never overwriting an existing known value with a (conflicting) known value; this should never be possible
//Unlike Part 2, we don't need to take the modulus because the wheel size has been set to the length of the text
if learnedWheels[5+i][index] != nil && *learnedWheels[5+i][index] != bit {
panic(fmt.Errorf("error: inconsistent transposition bit saved at %d for wheel %d", index, 5+i))
}
//Store the bit in the collection of learned wheels
learnedWheels[5+i][index] = &bit
}
}
} else {
TickAll(wheels)
}
}
}
//learnHardTransposeBits will learn the missing transpose bits in wheel 9, assuming all of wheels 5-8 are known
//It WILL call ResetWheels() as part of its execution, which will reset wheel state.
func learnHardTransposeBits(wheels []*Wheel, learnedWheels [][]*int, plaintext, ciphertext string) error {
//Reset the wheels
//This is VERY IMPORTANT, or the learning will fail.
ResetWheels(wheels)
//Assume that any remaining "nil" values appear on wheel 9
//This lets us update the missing spoke values on wheel 9, given
//the values on wheels 5-8
unknownSpokeIndices := map[int]struct{}{}
for _, wheel := range learnedWheels[5:10] {
for i, w := range wheel {
if w == nil {
unknownSpokeIndices[i] = struct{}{}
}
}
}
for index, plainRune := range plaintext {
plainChar := string(plainRune)
plainInt := alphabet[plainChar]
cipherRune := rune(ciphertext[index])
cipherChar := string(cipherRune)
cipherInt := alphabet[cipherChar]
present := false
if _, ok := interestingCharacters[cipherChar]; ok {
if _, ok := unknownSpokeIndices[index%LARGE_WHEEL_SIZES[9]]; ok {
present = true
xoredValue := xorCurrentCharacter(wheels, plainInt)
sourceIndex, err := FindUniqueBitIndex(xoredValue)
if err != nil {
panic(err)
}
destIndex, err := FindUniqueBitIndex(cipherInt)
if err != nil {
panic(err)
}
if destIndex == 4 {
if sourceIndex == 0 {
//We have already assumed that we know every spoke for every wheel but wheel 9 at this point
tmp := 1 - wheels[5].Items[index%LARGE_WHEEL_SIZES[5]]
learnedWheels[9][index%LARGE_WHEEL_SIZES[9]] = &tmp
//The value is no longer unknown, so remove it from the set of unknownSpokeIndices
delete(unknownSpokeIndices, *learnedWheels[9][index%LARGE_WHEEL_SIZES[9]])
}
if sourceIndex == 4 {
tmp := wheels[5].Items[index%LARGE_WHEEL_SIZES[5]]
learnedWheels[9][index%LARGE_WHEEL_SIZES[9]] = &tmp
delete(unknownSpokeIndices, *learnedWheels[9][index%LARGE_WHEEL_SIZES[9]])
}
} else if destIndex == 3 {
if sourceIndex == 4 {
tmp := 1 - wheels[5].Items[index%LARGE_WHEEL_SIZES[5]]
learnedWheels[9][index%LARGE_WHEEL_SIZES[9]] = &tmp
delete(unknownSpokeIndices, *learnedWheels[9][index%LARGE_WHEEL_SIZES[9]])
} else if sourceIndex == 0 {
tmp := wheels[5].Items[index%LARGE_WHEEL_SIZES[5]]
learnedWheels[9][index%LARGE_WHEEL_SIZES[9]] = &tmp
delete(unknownSpokeIndices, *learnedWheels[9][index%LARGE_WHEEL_SIZES[9]])
}
}
}
if !present {
//The wheels have only been incremented if xoredValue was called
TickAll(wheels)
}
} else {
TickAll(wheels)
}
}
//Check if all bits of all wheels have been learned
//If all bits of all wheels have not been learned by this point, throw an error
for wheelIndex, wheel := range learnedWheels {
for i, w := range wheel {
if w == nil {
return fmt.Errorf("error: wheel %d spoke %d is unknown", wheelIndex, i)
}
}
}
wheels = append(wheels, learnedWheelToWheel(learnedWheels[9]))
return nil
}
//removePossibleWheelState will remove the impossibleSize from the list of possible sizes for wheel with index wheelIndex in the set of possible sizes
func removePossibleWheelState(possibleSizes []map[int]struct{}, wheelIndex, impossibleSize int) []map[int]struct{} {
//Remove it from the list of possible sizes for the specified wheel iff it is present
if _, ok := possibleSizes[wheelIndex][impossibleSize]; ok {
delete(possibleSizes[wheelIndex], impossibleSize)
//If there is only one possibility left, we know this wheel with certainty
//Delete this size from all other wheels
if len(possibleSizes[wheelIndex]) == 1 {
//TODO figure out better hack
var actualSize int
for k, _ := range possibleSizes[wheelIndex] {
actualSize = k
break
}
for i, _ := range possibleSizes {
if i != wheelIndex {
possibleSizes = removePossibleWheelState(possibleSizes, i, actualSize)
}
}
}
}
return possibleSizes
}
// CrackMessage will read a file containing a series of encrypted messages (one per line)
// and determine the wheel order and values from the messages
// It assumes that plaintext messages begin with "UMUM4VEVE35"
// and end with "35"
// It will fail if there are not enough messages to determine wheel order fully
func crackMessage(filename string) []*Wheel {
//TODO rename this
var learnedWheels = [][]*int{}
//Use the LARGE wheel sizes instead of the regular wheel sizes this time
for i := 0; i < 10; i++ {
tmp_wheel := make([]*int, LARGE_WHEEL_SIZES[i])
learnedWheels = append(learnedWheels, tmp_wheel)
}
ciphertext, plaintext := parseCiphertext(filename)
//Learn all bits of the first five wheels
//The results are stored in learnedWheels (global variable)
learnFirstFiveWheels(learnedWheels, plaintext, ciphertext)
POSSIBLE_SIZES := make([]map[int]struct{}, 10)
for i, _ := range POSSIBLE_SIZES {
POSSIBLE_SIZES[i] = map[int]struct{}{
47: {},
53: {},
59: {},
61: {},
64: {},
65: {},
67: {},
69: {},
71: {},
73: {},
}
}
for i := 0; i < 5; i++ {
for size := range POSSIBLE_SIZES[i] {
for spokeIndex := 0; spokeIndex < size; spokeIndex++ {
impliedBit := -1
for index := spokeIndex; index < len(plaintext); index += size {
currentBit := learnedWheels[i][index]
if currentBit != nil {
if impliedBit == -1 {
impliedBit = *currentBit
} else if impliedBit != *currentBit {
//This means we have found a conflict
//Remove this wheel size from the pool of possible wheel sizes for this wheel
POSSIBLE_SIZES = removePossibleWheelState(POSSIBLE_SIZES, i, size)
}
}
}
}
}
}
//At this point, all of the first five wheels should be known
//This is not always the case, but it will be the case for the current input
//TODO account for the case in which the ciphertext is not long enough to learn all of the first five wheels
//Now, we know the bits of wheels 0-4, but they are in the wrong locations
//Set those bits to the correct locations
for i, _ := range POSSIBLE_SIZES[:5] {
//TODO figure out better hack
var wheelSize int
for k, _ := range POSSIBLE_SIZES[i] {
wheelSize = k
break
}
for j, _ := range learnedWheels[i] {
if learnedWheels[i][j] != nil {
learnedWheels[i][j%wheelSize] = learnedWheels[i][j]
}
}
}
//Truncate the first five wheels to their correct sizes
for i, _ := range learnedWheels[:5] {
//TODO figure out better hack
var wheelSize int
for k, _ := range POSSIBLE_SIZES[i] {
wheelSize = k
break
}
learnedWheels[i] = learnedWheels[i][:wheelSize]
}
//At this point, we know all the bits on the first five wheels
//AND they are in the correct locations
//We are ready to create Wheel structs for the first five wheels
wheels := make([]*Wheel, 5)
//Create actual Wheel structs for these fully-learned wheels and append them to "wheels" (global variable)
for wheelIndex, lw := range learnedWheels[:5] {
items := make([]int, len(lw))
for i, item := range lw {
items[i] = *item
}
wheel := NewWheel(items)
wheels[wheelIndex] = wheel
}
//Now, we need to do the same thing, but for wheels 5-9
//Learn the transpose bits, though they will not be in the correct locations
learnEasyTransposeBits(wheels, learnedWheels, plaintext, ciphertext)
//Figure out the actual sizes for wheels 5-9, so we can set the learned bits to be in the correct locations
for i := 5; i < 10; i++ {
for size := range POSSIBLE_SIZES[i] {
for spokeIndex := 0; spokeIndex < size; spokeIndex++ {
impliedBit := -1
for index := spokeIndex; index < len(plaintext); index += size {
currentBit := learnedWheels[i][index]
if currentBit != nil {
if impliedBit == -1 {
impliedBit = *currentBit
} else if impliedBit != *currentBit {
//This means we have found a conflict
//Remove this wheel size from the pool of possible wheel sizes for this wheel
POSSIBLE_SIZES = removePossibleWheelState(POSSIBLE_SIZES, i, size)
}
}
}
}
}
}
//At this point, all sizes for all wheels are known
//Now, we know the bits of wheels 5-9, but they are in the wrong locations
//Set those bits to the correct locations
for i, _ := range POSSIBLE_SIZES[5:] {
//TODO figure out better hack
var wheelSize int
for k, _ := range POSSIBLE_SIZES[5+i] {
wheelSize = k
break
}
for j, _ := range learnedWheels[5+i] {
if learnedWheels[5+i][j] != nil {
learnedWheels[5+i][j%wheelSize] = learnedWheels[5+i][j]
}
}
}
//Truncate the first five wheels to their correct sizes
for i, _ := range learnedWheels[5:] {
//TODO figure out better hack
var wheelSize int
for k, _ := range POSSIBLE_SIZES[5+i] {
wheelSize = k
break
}
learnedWheels[5+i] = learnedWheels[5+i][:wheelSize]
}
//We are ready to create Wheel structs for wheels 5-9
//Create actual Wheel structs for these fully-learned wheels and append them to "wheels" (global variable)
for _, lw := range learnedWheels[5:] {
items := make([]int, len(lw))
for i, item := range lw {
items[i] = *item
}
wheel := NewWheel(items)
wheels = append(wheels, wheel)
}
//TODO this is a global variable; it should eventually not be
return wheels
}
//Utility function for testing only
func printWheels(wheels []*Wheel) {
for _, wheel := range wheels {
log.Print(wheel)
}
}